3

I am calling a webservice which return me back a json object. The json object encodes the date. I am trying to find a way to convert that date to m-d-Y format in php. Json object is {"DateOfBirth":"/Date(387518400000-0400)/"} this date is 02-15-1982.

The webservice which I am calling is in .NET, and it converts the date to the JSON object. Not sure if this would help.

Thanks in advance

Thanks, Tanmay

2
  • Is that 04-12-1982 by chance, and not 02-15-1982? Commented Jul 26, 2010 at 21:43
  • Using AinStain's solution (which is necessary if the dates are negative (before 1970) that date seems to be 1982-04-13. Commented Apr 3, 2017 at 5:13

5 Answers 5

4

I know this question/answer is old, but I wanted to add that the @hookedonwinter answer is no longer correct. While his answer may have solved the specific solution, here in 2012 we now have an extra decimal place to take care of.

echo parseJsonDate('/Date(1336197600000-0600)/', 'date');

public function parseJsonDate($date, $type = 'date') {
    preg_match( '/\/Date\((\d+)([+-]\d{4})\)/', $date, $matches); // Match the time stamp (microtime) and the timezone offset (may be + or -)

    $date = date( 'm-d-Y', $matches[1]/1000 ); // convert to seconds from microseconds

    switch($type)
    {    
        case 'date':
            return $date; // returns '05-04-2012'
            break;

        case 'array':
            return explode('-', $date); // return array('05', '04', '2012')
            break;

        case 'string':
            return $matches[1] . $matches[2]; // returns 1336197600000-0600
            break;
    }    
}   
Sign up to request clarification or add additional context in comments.

Comments

3

@Brombomb

Your Function works fine, but there is one thing you forgot. Timestamps can be negative for Dates before the 01.01.1970, so we need a different regEx

I used this one and it works fine:

preg_match( '/\/Date\((-?\d+)([+-]\d{4})\)/', $date, $matches);

At the end i modified your Function a little bit to become more usefull for me. Now i can decide if i get the Date back as

  • "date" => date only
  • "time" => time only
  • "datetime" => date and time
  • "array" => date and time as an array
  • "string" => the timestamp as a string

and i can decide if i want the difference to the UTC timezone added/substracted when i give the third parameter...

function parseJsonDate($date, $type = 'date', $utc = 0) {
    // Match the time stamp (microtime) and the timezone offset (may be + or -) and also negative Timestamps
    preg_match( '/\/Date\((-?\d+)([+-]\d{4})\)/', $date, $matches);

    $seconds  = $matches[1]/1000;                // microseconds to seconds
    $UTCSec   = $matches[2]/100*60*60;           // utc timezone difference in seconds

    if($utc != 0){
        $seconds  = $seconds + $UTCSec; // add or divide the utc timezone difference
    }

    $date     = date( 'Y-m-d', $seconds );       // only date
    $dateTime = date( 'Y-m-d H:i:s', $seconds ); // date and time
    $time     = date( 'H:i:s', $seconds );       // only time

    switch($type)
    {
        case 'date':
            return $date; // returns 'YYYY-MM-DD'
            break;

        case 'datetime':
            return $dateTime; // returns 'YYYY-MM-DD HH:ii:ss'
            break;

        case 'time':
            return $time; // returns 'HH:ii:ss'
            break;

        case 'array':
            $dateArray = str_replace(" ", "-", $dateTime);
            $dateArray = str_replace(":", "-", $dateArray);
            return explode('-', $dateArray); // return array('YYYY', 'MM', 'DD', 'HH', 'ii', 'SS')
            break;

        case 'string':
            return $matches[1] . $matches[2]; // returns 1336197600000-0600
            break;
    }
}

Comments

1

If there's a chance you said 02-15-1982 but really meant 04-12-1982, then I have a solution. If not, then there's a gap in the time of about 60 days, which can be accounted for with a bit more math.

Here's my solution for now:

date_default_timezone_set(  'America/Denver' );

$json = json_decode( '{"DateOfBirth":"\/Date(387518400000-0400)\/"}' );
$date_string = $json -> DateOfBirth;

preg_match( '/([\d]{9})/', $date_string, $matches ); // gets just the first 9 digits in that string

echo date( 'm-d-Y', $matches[0] );

This returns: 04-12-1982

11 Comments

@hookedonwinter: Thanks for you reply but, the date is 02/15/1982. For me today the json object was like - {"DateOfBirth":"\/Date(382597200000-0500)\/"} again this is 02/15/1982. I did discuss with the .NET developer of the webservice, he says like .NET it self parses the date for him and creates the JSON object for him. So it seems .NET is doing some specific conversion!!! let me add .NET TAG, if some one might know. Thanks for your help though.
In your comment you have the value 382597200000, but in your question you have 387518400000. You say that both are 02-15-1982, but I believe like @hookedonwinter that there is an error in the date specified in the question. hookedonwinter's solution works well if this is the case, so I'm voting it up.
@kevin: I believe as its a timestamp, number would change every day. The number I asked 387518400000-0400, was yesterday. Please let me know if I am wrong. @hookedonwinter: Your logic did work for me except, if I do set the timezone, as you are doing in your code, it gives me 04-12-192, BUT if I don't specify the timezone it gives me 02-15-1982. Currently I am in EST timezone. I don't have much experience on datetime. But your suggestion did work for me. Thanks a lot. Marking as the correct answer.
Well... That's just strange. But hey, it works ::applies band-aid::
@jtanmay - The whole thing doesn't seem like a timestamp. The first 9 digits of the first part are, which is why hookedonwinter's solution pulls these out. I'd venture a guess that the "-0500" part is the time zone offset, but I don't know what the other 3 digits are for. With regards to timezone, since php 5.1.0 you should always have a default set if you are going to be using php functions (see php.net/manual/en/function.date-default-timezone-set.php), so you might want to consider investigating that further at some point.
|
1

You can use this package to parse the JSON dates:

https://github.com/webapix/dot-net-json-date-formatter

use \Webapix\DotNetJsonDate\Date;

Date::toDateTime('/Date(387518400000-0400)/'); // return with \DateTime object

Comments

0

@Brombomb in my case I added to your function an other parameter to return a Date Object:

public function parseJsonDate( $date, $type = 'date' )
{
    // removes extra millisecond digits in an other reg exp class
    preg_match( '/\/Date\((\d{10})\d+([+-]\d{4})\)/', $date, $matches ); // Match the time stamp (microtime) and the timezone offset (may be + or -)

    $date = date( 'm-d-Y', $matches[1] );

    switch( $type )
    {
        case 'dateTimezone':
            return DateTime::createFromFormat( 'UT', $matches[1] . $matches[2] );

        case 'date':
            return $date; // returns '05-04-2012'
            break;

        case 'array':
            return explode( '-', $date ); // return array('05', '04', '2012')
            break;

        case 'string':
            return $matches[1] . $matches[2]; // returns 1336197600000-0600
            break;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.