Presse
Presse

Reputation: 418

Convert Long to DateTime in Windows Phone C#

I am getting requests from API for my app. In that the date/time is claimed to be in the format of Long. I am trying to convert it using the following lines.

DateTime? dt = new DateTime(long.Parse(detail.CREATEDTIME));
MessageBox.Show(detail.CREATEDTIME + "=>" + dt.Value.ToString("yyyy-MM-dd"));

The actual output is as follows:

1393559958788=>0001-01-02

But the expected output is as follows:

1393559958788=>2014-02-28

The expected output is from java. How do i do this with C#?

Upvotes: 1

Views: 178

Answers (2)

RB.
RB.

Reputation: 37192

Most likely, the long value represents a Unix Timestamp.

Check this question for how to convert.

However, note that your values appear to be milliseconds since 1/1/1970, not seconds, so you may need to use .AddMilliseconds, rather than .AddSeconds,

The code I used to confirm this was:

DateTime d = new DateTime(1970, 1, 1,0,0,0,0,DateTimeKind.Utc).AddMilliseconds(1393559958788);
Console.WriteLine(d); // 28/02/2014 03:59:18

Upvotes: 4

Nicolas Tyler
Nicolas Tyler

Reputation: 10552

This is what you are looking for:

DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
dt = dt.AddMilliseconds(long.Parse(detail.CREATEDTIME)).ToLocalTime();
MessageBox.Show(detail.CREATEDTIME + "=>" + dt.Value.ToString("yyyy-MM-dd"));

Upvotes: 1

Related Questions