Home > Blockchain >  Converting a 24 hr time string to datetime and keeping the 24 hr time
Converting a 24 hr time string to datetime and keeping the 24 hr time

Time:11-16

I'm at a loss here, and I realise I may be going the long way around, but I can't figure it out. I have a datetime in UTC, curr. It is not being saved in 24 hr time, so I can convert it to a string s, which is indeed a string in 24 hr time. Now I want to save it back as a datetime still retaining the 24 hr time, but when I write foo out it is still being displayed in 24 hr time. How do I get the current Utc time in not just a DateTime, but a 24 hr DateTime?

var curr = DateTime.UtcNow;
String s = curr.ToString("yyyy-MM-dd HH:mm:ss");
DateTime foo = DateTime.Parse(s);
Console.WriteLine(foo);
Console.ReadLine();

CodePudding user response:

A DateTime just has a value not a format, so this is wrong: "It is not being saved in 24 hr time", because "24hr time" is about a formatted-datetime-string.

Console.WriteLine(foo) calls DateTime.ToString without parameters. Depending on your current culture you will then get a formatted datetime-string. If you want to ensure a specific format, use DateTime.ToString with a culture and/or a format string(like you did).

So a DateTime is just a value(ticks since January 1, 0001). If you want to display it use DateTime.ToString, until then keep it as a DateTime.

Read: Standard date and time format strings and Custom date and time format strings

CodePudding user response:

The DateTime object does not store time in the form of hours/minutes/seconds as we traditionally think of time, instead under the hood it is storing the number of "ticks" (100 nanosecond intervals) since a beginning point (I believe 1st January 1AD).

When you call .ToString() on a DateTime object, it will default to the standard date format encoded, which is the AM/PM format.

If you want it to display as 24hr time then you have to give it a format as you did here:

String s = curr.ToString("yyyy-MM-dd HH:mm:ss");

  • Related