【问题标题】:C# an application requires date formats to be converted into one common date format应用程序需要将日期格式转换为一种常见的日期格式
【发布时间】:2021-12-28 14:46:20
【问题描述】:

有人向我提出了将多种日期格式转换为单一格式的问题。

我已经获得了一些代码开始,但我仍在学习 C# 的基础知识并理解一般问题并进行了一些研究,但仍然不确定如何准确解决问题,如果有人可以提供一些指导或建议我将不胜感激,谢谢。

using System;
using System.Collections.Generic;

namespace CommonDateFormat
{
  public  class DateTransform
    {
        public static List<string> TransformDateFormat(List<string> dates)
        {
            throw new InvalidOperationException("Waiting to be implemented.");
        }

        static void Main(string[] args)
        {
            var input = new List<string> { "2010/02/20", "19/12/2016", "11-18-2012", "20130720" };
            DateTransform.TransformDateFormat(input).ForEach(Console.WriteLine);
        }
    }
}

Picture of the Question

【问题讨论】:

    标签: c# .net datetime datetime-format


    【解决方案1】:

    让我们从改造单个DateTime开始:

    • 我们可以将TryParseExact给定的字符串转换成DateTime
    • 然后我们可以将DateTime 表示为所需的“标准”格式:
        using System.Globalization;
        using System.Linq;
        
        ...
    
        private static string ConvertToStandard(string value) {
          if (DateTime.TryParseExact(value,
                //TODO: add more formats here if you want
                new string[] { "yyyy/M/d", "d/M/yyyy", "M-d-yyyy", "yyyyMMdd"},
                CultureInfo.InvariantCulture,
                DateTimeStyles.AssumeLocal,
                out var date))
            return date.ToString("yyyyMMdd"); //TODO: Put the right format here
          else // parsing failed. You may want to throw new ArgumentException here
            return value;
        }
    

    如果我们有一个List&lt;string&gt;,我们可以在 Linq 的帮助下查询它:

      List<string> original = new List<string>() {
        "2010/02/20", "19/12/2016", "11-18-2012", "20130720",
      };
    
      var result = original.Select(item => ConvertToStandard(item));
    
      // Let's have a look:
      Console.Write(string.Join(", ", result));
    

    或者如果你想要一个方法:

      public static List<string> TransformDateFormat(List<string> dates) {
        if (dates == null)
          throw new ArgumentNullException(nameof(dates));   
        
        return dates.Select(s => ConvertToStandard(s)).ToList();
      } 
    

    结果: (Fiddle)

      20100220, 20161219, 20121118, 20130720
    

    【讨论】:

    • 非常感谢
    猜你喜欢
    • 2017-08-27
    • 2011-11-23
    相关资源
    最近更新 更多