简体   繁体   中英

Converting a string into a 24hr datetime format

I have string data that comes in the following sequence:

"4:32", "1:08"

I want to convert this to 24hr time

where "4:32" becomes 16:32

Parse that to a TimeSpan , then add 12 hours:

var offset = TimeSpan.FromHours(12);
var time = TimeSpan.Parse("4:32").Add(offset);

Parse the input string to a TimeSpan , add 12 hours, then format the TimeSpan with the desired string format:

string input = "4:32";
string output = TimeSpan.Parse(input).Add(TimeSpan.FromHours(12)).ToString("hh\\:mm");

// output: "16:32"

As per your comment, once you know if the hour is AM/PM, you could parse the value with it's suffix and then use the HH custom format specifier:

DateTime d = DateTime.Parse("4:32 PM");
Console.WriteLine(d.ToString("HH:mm"));

to convert it to 24h format.

https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings#HH_Specifier

In the simple case your question suggests, where you know beforehand that the string is 12-hour in the format h:mm and it refers to PM, never AM, then you can split the string, parse the hour, add 12, and reassemble it.

var inputString = "4:32";
var splits = inputString.Split(':');
var hourString = splits[0];
var minuteString = splits[1];
var hour = int.Parse(hourString);
hour = hour + 12;
var outputString = $"{hour}:{minuteString}";

If you're doing anything more complicated with dates or times, you probably want to use DateTime or similar classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM