应用程序需要将日期格式转换为一种通用日期格式

An application requires date formats to be converted into one common date format

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

我已经获得了一些开始的代码,但我仍在学习 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

让我们从改造单身开始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<string>,我们可以借助 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