2

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?

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
webworm
  • 10,587
  • 33
  • 120
  • 217
  • new DateTime(Year, Month, Day); – Russ Jan 07 '21 at 21:18
  • 1
    Be very careful parsing things this way; on my system `DateTime.Parse("June 6")` proceeds without error to give the utterly erroneous result of 2006-06-01. `DateTime.Parse("June 6", new CultureInfo("en-US"))` does the right thing, but even then I'm not sure I wouldn't be more comfortable doing the parsing myself, with a fixed list of month names. – Jeroen Mostert Jan 07 '21 at 21:21
  • `DateTime.ParseExact(date + " 2020", "MMMM d yyyy", System.Globalization.CultureInfo.InvariantCulture)`? – juharr Jan 07 '21 at 21:32

3 Answers3

2

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
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
1

One line can do it:

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

DateTime date = Convert.ToDateTime(desiredYear.ToString() + textDate);
Gustav
  • 53,498
  • 7
  • 29
  • 55
0

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);
John Wu
  • 50,556
  • 8
  • 44
  • 80