Home > Back-end >  An application requires date formats to be converted into one common date format
An application requires date formats to be converted into one common date format

Time:12-30

I have been provided with a question to transform multiple date formats into a single format.

I have been given some code to start with but I am still learning the basics of C# and understood the questions in general and have carried out some research and still not sure exactly how to exactly tackle the problem, if anyone could provide some guidance or advice I would appreciate it, Thanks.

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

CodePudding user response:

Let's start from transforming single DateTime:

  • We can TryParseExact given string into DateTime
  • Then we can represent DateTime into required "standard" format:
    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;
    }

If we have a List<string> we can query it with a help of 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));

Or if you want a method:

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

Outcome: (Fiddle)

  20100220, 20161219, 20121118, 20130720
  • Related