Quantcast
Viewing all articles
Browse latest Browse all 275

.NET DateTime to JSON UNIX JavaScript datetime

When posting datetimes to web services or REST services, you might need to convert the standard .NET DateTime to a UNIX format.

Please note than neither REST, nor JavaScript has its own DateTime format. But some systems based on REST (Java applications for example) have a love affair with the UNIX Epoch datetime format, which is the number of seconds since 1/1/1970.

So in order to convert a standard .NET DateTime to a number of seconds, you need to calculate the TimeSpan between the current DateTime and 1/1/1970:

public string ToUnixEpoch(DateTime dateTime)
{
  DateTime d1 = new DateTime(1970, 1, 1);
  DateTime d2 = dateTime.ToUniversalTime();
  TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
  return ts.TotalMilliseconds.ToString("#");
}

The string returned contains the integer of the timespan.

In some systems you need to add /Date()/ around your timespan, so the resulting UNIX Epoch string looks like this:

/Date(1234567891234)/

To convert the UNIX datetime to a .NET DateTime you reverse the process:

public DateTime FromUnixEpoch(long epochTime)
{
    var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    return epoch.AddSeconds(epochTime);
}

Some systems will return the UTC time, not the time from the current timezone. To convert from UTC to the current timezone, use the TimeZone class from .NET:

TimeZone.CurrentTimeZone.ToLocalTime(yourutctime)

 


Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 275

Trending Articles