0

Hello guys i am trying to convert the date to UNIX timestamp but i get an error while converting it with some specific dates

string         zoho_meeting_start_date_time = result.Value<JObject>()["Start_DateTime"].Value<String>();
DateTimeOffset dateTimeOffSet               = DateTimeOffset.Parse(zoho_meeting_start_date_time);

zoho_meeting_start_date_time_timestamp = dateTimeOffSet
    .ToUnixTimeMilliseconds()
    .ToString();
  • When I have the date for example : "08/01/2022 17:00:00" it gets converted perfectly fine to 1641657600000.

  • When I get the date "07/28/2022 16:00:00" I get this error:

    System.FormatException: String '07/28/2022 16:00:00' was not recognized as a valid DateTime.

Dai
  • 141,631
  • 28
  • 261
  • 374
redbeard
  • 39
  • 3
  • see this link https://stackoverflow.com/questions/249760/how-can-i-convert-a-unix-timestamp-to-datetime-and-vice-versa – onoffon Aug 03 '22 at 09:00

1 Answers1

4

That's because 1641657600000 is Saturday 8th January 2022 and the date string is being interpreted as dd/MM/yyyy HH:mm:ss. Now when you try it with 07/28/2022, 28 is an invalid value for month and the error is thrown.

What you need to do is use DateTimeOffset.ParseExact and specify explicitly the format MM/dd/yyyy HH:mm:ss as this is not the default.

DateTimeOffset.ParseExact(zoho_meeting_start_date_time, "MM/dd/yyyy HH:mm:ss", null);
phuzi
  • 12,078
  • 3
  • 26
  • 50
  • Why would DateTimeOffset use CurrentCulture? running it on dotnetfiddle seems fine: https://dotnetfiddle.net/zJDEG3 – Rand Random Aug 03 '22 at 09:04
  • Thank you for your help, but is the syntax correct bcs i get an error saying that "No overload for method Parse.Exact takes 2 arguments" – redbeard Aug 03 '22 at 09:05
  • By default DotNetFiddle use the InvariantCulture if you try flipping it to `28/07/2022` there then you get the same error OP is seeing. – phuzi Aug 03 '22 at 09:10
  • Nope, sorry. I've updated the code. If you're passing a specific format then You can pass a null IFormatProvider. – phuzi Aug 03 '22 at 09:13