简体   繁体   中英

DateTime ParseExtract seconds when ss is more than 59

s_Time = DateTime.ParseExact("113388", "HHmmss", null);

Getting Error when ss is more than 59. How can avoid this. If ss is more than 59 i want to display it as 00.

How can i achieve this?

Actually i have a file name which contains time to validate. ss will come randomly it may be 00 to 99, how ever i have to show 00 when its grater than 59

To follow up on my comment, something this makes the most sense to me. Treat the string as adding onto the hours and minutes that you parse.

var temp = "113388";
s_Time = DateTime.ParseExact(temp.Substring(0, 4
), "HHmm", null).AddSeconds(int.Parse(temp.Substring(4)));

I would only ever check this into production when the second hand says 88 though =)

Hexxagonal probably has the most sensible solution , but if you should for some reason want to replace the last part of the string (the seconds) with "00" when the value is above 59, and not update the minutes part, then this should work:

var input = "113388"; // original
var secsPart = input.Substring(4);
// Get 00 if over 59, else keep the seconds as they are:
var seconds = int.Parse(secsPart) > 59 ? "00" : secsPart; 
var editedInput = input.Substring(0,4) + seconds;

var s_Time = DateTime.ParseExact(editedInput, "HHmmss", null);

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