Search code examples
c#datetimedatetime-conversion

C# - Convert.ToDateTime() where Year is not specified in the Date


I would like to convert a list of dates that are represented as follows:

  • June 6
  • September 18
  • November 2
  • February 29

The dates themselves do not specify the year so when I attempt to parse them using Convert.ToDateTime() the current year (2021) is assumed. How can I specify these dates to be of a different year? Lets say I want to specify each of these dates are from the year 2020. How can I specify that in the conversion? Is this where I would use CultureInfo?


Solution

  • You can parse (ParseExact) the text provided; the only possible issue is leap year and February 29:

    private static DateTime MyConvert(string text, int year = 0) {
      return DateTime.ParseExact(
        $"{(year <= 0 ? DateTime.Today.Year : year)} {text}", 
        "yyyy MMMM d", 
        CultureInfo.InvariantCulture);
    }
    

    Demo:

      string[] tests = new string[] {
        "June 6",
        "September 18",
        "November 2",
        "February 29"
      };
    
      string report = string.Join(Environment.NewLine, tests
        .Select(test => $"{test,-15} => {MyConvert(test, 2000):dd.MM.yyyy}"));
    
      Console.Write(report);
    

    Outcome:

    June 6          => 06.06.2000
    September 18    => 18.09.2000
    November 2      => 02.11.2000
    February 29     => 29.02.2000