Unity c# convert date-string to datetime object in desired date time format

Mike picture Mike · Dec 16, 2018 · Viewed 8.9k times · Source

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!

Answer

Oscar picture Oscar · Dec 16, 2018

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://docs.microsoft.com/en-us/dotnet/api/system.datetime?view=netframework-4.7.2#datetime-values-and-their-string-representations