1

This is the code I got running:

string dateStart = "2020-03-03T20:12:15+00:00"
DateTime Start = DateTime.ParseExact(dateStart, "yyyy-MM-ddTHH:mm:sszzz", null);
long unixStart = ((DateTimeOffset)Start).ToUnixTimeSeconds();

Then it crash, this is the exception:

Excepción producida: 'System.ArgumentOutOfRangeException' en System.Private.CoreLib.dll
Excepción no controlada del tipo 'System.ArgumentOutOfRangeException' en System.Private.CoreLib.dll
The UTC time represented when the offset is applied must be between year 0 and 10,000.

Thanks!

unknown Javi
  • 41
  • 1
  • 9
  • Convert to UTC and subtract `DateTime.UnixEpoch`? `long unixStart = (long)Start.ToUniversalTime().Subtract(DateTime.UnixEpoch).TotalSeconds;` – mm8 Apr 01 '20 at 11:04
  • @mm8 please don't post answers in comments – Caius Jard Apr 01 '20 at 11:43
  • Does this answer your question? [How to get the unix timestamp in C#](https://stackoverflow.com/questions/17632584/how-to-get-the-unix-timestamp-in-c-sharp) – Caius Jard Apr 01 '20 at 11:44
  • this code cannot run because its missing ; in first line.. if added the code perfectly runs fine in .net core console app with result : 1583266335.. so kindly post the exact code you are using plus which .net framework or .net core you are using – Hany Habib Apr 01 '20 at 11:45
  • @HanyHabib I wrote the string here so I missed the ; but doesn't matter, it gives the exception there. Im using .NET CORE 3.1 – unknown Javi Apr 01 '20 at 12:13
  • Thanks for your answer but I dont know how to convert it @mm8 – unknown Javi Apr 01 '20 at 12:13
  • thats weird i ran the same example in .net core 3.1 also console app and it ran and i posted the result to:1583266335.. can your provide the whole piece of code.. as it should be working fine .. – Hany Habib Apr 01 '20 at 12:23
  • @unknownJavi: See my answer. – mm8 Apr 01 '20 at 12:28

1 Answers1

2

Try to convert to UTC and subtract DateTime.UnixEpoch:

string dateStart = "2020-03-03T20:12:15+00:00";
DateTime Start = DateTime.ParseExact(dateStart, "yyyy-MM-ddTHH:mm:sszzz", System.Globalization.CultureInfo.InvariantCulture);

long unixStart = (long)Start
    .ToUniversalTime()
    .Subtract(DateTime.UnixEpoch)
    .TotalSeconds;
mm8
  • 163,881
  • 10
  • 57
  • 88
  • Thanks for your answer, conversion was done but all milliseconds are like this: `-62135596800 = Fri Jan 12 1968 20:06:43` ||||| `2020-03-01T21:00:00+00:00` that was the string I inputed. – unknown Javi Apr 01 '20 at 12:35
  • @unknownJavi: No, the code above gives `1583266335` and nothing else. Try to copy and paste it into your IDE: – mm8 Apr 01 '20 at 12:41
  • @mm8 this is the same value i posted up with his same code .. are you facing the same exception if you used his code ?.. – Hany Habib Apr 01 '20 at 12:44