1

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?

adamj537
  • 677
  • 7
  • 14
  • Does this answer your question? [c# Parsing UTC datetime](https://stackoverflow.com/questions/7913559/c-sharp-parsing-utc-datetime) – gunr2171 May 10 '22 at 21:30
  • "Is there a TryParse method" try looking up "c# DateTime TryParse". – gunr2171 May 10 '22 at 21:31
  • See also [Parse string to DateTime in C#](https://stackoverflow.com/questions/5366285/parse-string-to-datetime-in-c-sharp) – gunr2171 May 10 '22 at 21:32
  • See also [Parse C# string to DateTime](https://stackoverflow.com/questions/7580809/parse-c-sharp-string-to-datetime) – gunr2171 May 10 '22 at 21:32
  • Make sure you understand what you are getting back. GPSes speak a whole different time language than anything else (weird year, week and day behavior, no leap seconds, etc.): https://timetoolsltd.com/gps/what-is-gps-time/ – Flydog57 May 10 '22 at 21:51

1 Answers1

2

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.

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
phuzi
  • 12,078
  • 3
  • 26
  • 50
  • 1
    I edited your question. Invariant culture will prevent localization edge cases, but also it will be important to pass the styles flags so the value is both parsed and returned as UTC rather than local kind. – Matt Johnson-Pint May 10 '22 at 21:54