1

This is such a Date I have from a JSON:

"created_time": "1383734307"

So my code is:

var myData = DateTime.ParseExact((string)item.created_time, "ddd MMM dd HH:mm:ss zzzz yyyy", CultureInfo.InvariantCulture);

but I get String was not recognized as a valid DateTime.

markzzz
  • 47,390
  • 120
  • 299
  • 507

5 Answers5

6

Your number 1383734307, looks like number of seconds elapsed since 1970/01/01 (Unix Epoch) you can do the following to get the DateTime

DateTime dt = new DateTime(1970, 1, 1).AddSeconds(1383734307);

This will return : dt = {06/11/2013 10:38:27 AM}

Currently the format you are using to parse DateTime is invalid.

For your case it appears that created_time is of type long/int, since you are casting it to string, you can do:

DateTime dt = new DateTime(1970, 1, 1).AddSeconds(created_time);

Or you can parse it to long like:

DateTime dt = new DateTime(1970, 1, 1).AddSeconds(Convert.ToInt64(created_time));
Habib
  • 219,104
  • 29
  • 407
  • 436
2

First of all, your data is not a DateTime, it is a timestamp. So check this question how to make DateTime from it: How to convert UNIX timestamp to DateTime and vice versa?.

For c# it would be:

public static DateTime UnixTimeStampToDateTime( double unixTimeStamp )
{
    // Unix timestamp is seconds past epoch
    System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0);
    dtDateTime = dtDateTime.AddSeconds( unixTimeStamp ).ToLocalTime();
    return dtDateTime;
}

Then, you can use ToString method, to generate datatime string from your DateTime instance, which matches your format:

var dateString = myDateTime.ToString("ddd MMM dd HH:mm:ss zzzz yyyy", CultureInfo.InvariantCulture);
Community
  • 1
  • 1
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
1

That looks like a Unix (seconds past epoch) Timestamp:

You need something like this

var dateTime = new DateTime(1970,1,1,0,0,0,0);
dateTime = dateTime .AddSeconds( unixTime ).ToLocalTime();
Science_Fiction
  • 3,403
  • 23
  • 27
0

You need to convert from epoch time to DateTime in C#, check this answer with the code to do the conversion: https://stackoverflow.com/a/2883645/892290

Community
  • 1
  • 1
majimenezp
  • 302
  • 2
  • 3
0

Try this:

new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(long.Parse((string)item.created_time));
mehmet mecek
  • 2,615
  • 2
  • 21
  • 25