0

I have the time in milliseconds as a string like this: 229935440730121 How to convert this string to a DateTime object.
Thanks

Update

Sorry, The correct string is : 1423509923000 and should be 2/9/15 7:25:23 PM after conversion. It's a time string received from an telemetry device.

a.toraby
  • 3,232
  • 5
  • 41
  • 73
  • 3
    Presumably it's a number of milliseconds since an epoch - probably the unix epoch? So first parse it to a `long`, and then add that number of milliseconds to a `DateTime` representing that epoch... – Jon Skeet Feb 09 '15 at 15:21
  • 2
    Seems a duplicate http://stackoverflow.com/questions/7336932/how-to-convert-milliseconds-to-date-format-in-c – Kavindu Dodanduwa Feb 09 '15 at 15:22
  • 1
    Tim - that will throw an overflow exception. You'll need `long.Parse` for a number that large. – Ed Gibbs Feb 09 '15 at 15:24
  • `229935440730121` milliseconds is about `7286` years. Check if you have computed the argument right. – Dmitry Bychenko Feb 09 '15 at 15:28
  • @DmitryBychenko: perhaps it's already the sum, f.e. of man-days. However, it sounds as if a `TimeSpan` is more appropriate anyway. For example: `TimeSpan.FromMilliseconds(229935440730121)` – Tim Schmelter Feb 09 '15 at 15:36

1 Answers1

4

Milliseconds is a duration, not a time. You can convert it to a TimeSpan easily:

string ms = "229935440730121";
TimeSpan ts = TimeSpan.FromMilliseconds(double.Parse(ms));

To convert to a DateTime you need to know the reference point from which the span was measured, then just add the TimeSpan to that date:

DateTime dt = DateTime.MinValue;  // for example only
dt += ts;  // add the timespan to the date

In your example, that number of milliseconds represents over 7,280 years, so it's not clear what the reference point should be.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • The correct string was 1423509923000. And this is the given number of milliseconds that have passed since 1970-01-01T00:00:00, Coordinated Universal Time. I replaced `DateTime.MinValue` with `DateTime.Parse("1970-01-01T00:00:00")` and it works perfect. Thanks – a.toraby Feb 09 '15 at 16:16