'How to compare string "203658.000" to UTC in C#?
I have a string "203658.000" which encodes UTC time from a GPS receiver.
The format is "hhmmss.ffff", where:
- "hh" is hours (fixed two digits)
- "mm" is minutes (fixed two digits)
- "ss" is seconds (fixed two digits)
- "fff" is decimal fraction of seconds (variable length)
I'd like to know if the time is correct. To do that, I think I should convert the string to a DateTime, then compare it to DateTime.UtcNow.
Here is my code so far:
int timestamp = (int)Convert.ToDouble("203658.000");
int hours = (timestamp % 1000000 - timestamp % 10000) / 10000;
int minutes = (timestamp % 10000 - timestamp % 100) / 100;
int seconds = timestamp % 100;
DateTime dateTime = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, hours, minutes, seconds);
if (DateTime.UtcNow.Equals(dateTime))
{
// Pass
}
Is there a TryParse method to do this instead of extracting hours, minutes, and seconds mathematically?
Solution 1:[1]
You should be able to use DateTime.ParseExact to get what you need.
DateTime.ParseExact("203658.000", "HHmmss.fff", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal)
Be careful around midnight though, as the time could be nearly 24 hours out if the dates don't match.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Matt Johnson-Pint |
