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

Viewed 531

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?

3 Answers

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

One line can do it:

string textDate = "September 18";
int desiredYear = 2008;

DateTime date = Convert.ToDateTime(desiredYear.ToString() + textDate);

Just change the year post hoc.

var input = "June 6";
var converted = DateTime.ParseExact("mmmm d");
var date = new DateTime(DateTime.Today.Year, converted.Month, converted.Day);
Related