Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decode JSON date using php?

Tags:

php

I get from JSON output the date in JSON encrypt, I want to decode it when I insert it to mysql.

I insert the output:

"date": "/Date(1446739002960)/"

to $dateparse variable

I was write the solution using javascript:

var dateString = "\/Date(753343200000)\/".substr(6);
var currentTime = new Date(parseInt(dateString ));
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var date = day + "/" + month + "/" + year;
alert(date);

How can I decode the variable content using php? thank you

like image 302
Idan Neeman Avatar asked Jan 07 '23 02:01

Idan Neeman


1 Answers

Don't forget about timezone as JavaScript date string may include it and here is how you can parse it for both cases

// Let's assume you did JSON parsing and got your date string
$date = '/Date(1511431604000+0000)/';

// Parse the date to get timestamp and timezone if applicable
preg_match('/\/Date\(([0-9]+)(\+[0-9]+)?/', $date, $time);

// remove milliseconds from timestamp
$ts = $time[1] / 1000;
// Define Time Zone if exists
$tz = isset($time[2]) ? new DateTimeZone($time[2]) : null;

// Create a new date object from your timestamp
// note @ before timestamp
// and don't specify timezone here as it will be ignored anyway
$dt = new DateTime('@'.$ts);

// If you'd like to apply timezone for whatever reason
if ($tz) {
  $dt->setTimezone($tz);
}

// Print your date
print $dt->format('Y-m-d H:i:s');
like image 179
dgpro Avatar answered Jan 16 '23 02:01

dgpro