Search code examples
php.netdateunix-timestampint64

Convert Unix Timestamp to .net int64 datetime


First of all, I know that it's duplicate, but those questions aren't what I am looking for.

I'm using an API to add participants in an online application. When I post JSON object to endpoint, everything is posted except dates. There's some misunderstanding with date format. If I get existing participants and check the date format that's this:

{
   "participant":{  
      "ID":201954,
         //  Long Object
      "DateOfBirth":"\/Date(857305424000-0500)\/",
   }
}

I figured out that first 9 char are UNIX timestamp but rest of them?? not sure. Any idea what is this format?

EDIT Online application is made in .net/asp/c# not sure about them. But I am writing my code in php application which post json object via cURL

EDIT 2 I checked parsing wrong formats and got this error:

The value '0.48631700 1425319593' cannot be parsed as the type 'Int64'.'. Please see InnerException for more details.

Any idea how can I get the format of .net's int64 datetime in php?


Solution

  • JSON itself does not specify how dates should be formatted, so you need to know the requirements of the target .NET application. Most likely it makes sense to convert to a "readable" date format

    Example (php):

    $timestamp=1333699439;
    echo gmdate("Y-m-d\TH:i:s\Z", $timestamp); 
    // outputs 2012-04-06T08:03:59Z
    

    Example (.net):

    DateTime d;
    DateTime.TryParse("2012-04-06T08:03:59Z", out d); 
    // receives 4/6/2012 8:03:59 AM (in US-format)
    

    Edit:

    .NET int64 format is a number of ticks since midnight 0001-01-01 00:00:00 (every tick is 1/10000000 of second) and UNIX timestamp is number of seconds since beginning of the UNIX epoch (1970-01-01 01:00:00), so desired result is $seconds = 621355968000000000/10000000 - $number_of_seconds, see Convert ticks to unix timestamp and https://kramerc.com/2010/11/30/converting-datetime-ticks-into-a-unix-timestamp-in-php/

    Therefore, for JSON output you should do

    $timestamp=1333699439;
    $ticks = ($timestamp * 10000000) + 621355968000000000;
    // outputs 634692962390000000
    

    Test function php

    function ticks_to_time($ticks) {
        return floor(($ticks - 621355968000000000) / 10000000);
    }
    
    $time = ticks_to_time(634692962390000000);
    echo date("F j Y g:i:s A T", $time);
    // outputs April 6 2012 4:03:59 AM EDT
    

    Test function .net

    Int64 intDate = 634692962390000000; 
    DateTime dt = new DateTime(intDate); 
    Console.WriteLine(dt.ToString()); 
    // outputs 4/6/2012 8:03:59 AM