6

I need to convert a list of strings that contain date information (e.g. "2018-12-16") into DateTime format so that I can sort them all by date...and then convert back to string... I'm struggling to make this work. Testing on one of the strings:

string dateTimeString = "2018-12-16";
System.DateTime dateTime = System.DateTime.Parse(dateTimeString);
print(dateTime.ToString());

which prints "12/15/2018 12:00:00 AM" - but I don't want the time, and the format is different.. so I tried this (specifying the date format):

string dateTimeString = "2018-12-16";
System.DateTime.ParseExact(dateTimeString, new string[] { "yyyy-MM-dd" }, new System.Globalization.CultureInfo("en-AU"), System.Globalization.DateTimeStyles.None);
print(dateTime.ToString());

this has the same result.

I've tried making the format conversion going the other way:

string dateTimeString = System.String.Format("{0:yyyy-MM}", dateTime);
print(dateTimeString);

this also has the same result!

Can someone please help me, or point me in the direction of some decent documentation / examples? Thanks!

Mike
  • 133
  • 1
  • 1
  • 8
  • Right, so I can manually build my string from the dateTime: 'string dateTimeStr = dateTime.Day.ToString() + "-" + dateTime.Month.ToString() + "-" + dateTime.Year.ToString();' But there should be an easier way.. I would also like to exclude time from the dateTime variable so it sorts properly. – Mike Dec 16 '18 at 12:56

1 Answers1

8

Try this:

string dateTimeString = "2018-12-16";
System.DateTime dateTime = System.DateTime.Parse(dateTimeString);
print(dateTime.ToString("yyyy-MM-dd"));

More info can be found here: https://learn.microsoft.com/en-us/dotnet/api/system.datetime?view=netframework-4.7.2#datetime-values-and-their-string-representations

Oscar
  • 128
  • 1
  • 6