Home > database >  Want to convert javascript code to php but return values mismatched
Want to convert javascript code to php but return values mismatched

Time:07-28

I am trying to convert below javascript code

d1 = new Date("2022-01-13 00:00:00");
d2 = new Date();
d2.setTime(1641951202187.3433);  

console.log(d1,d2)
console.log(d1-d2); // returning value 60997813

PHP

date_default_timezone_set("Asia/Kolkata");   //India time (GMT 5:30)

$d1 = new DateTime("2022-1-13 00:00:00");
$mili = 1641951202187.3433;
$sec = $mili /1000;
$d = date('M-d-Y H:i:s',$sec);
$d2 = new Datetime($d);
$s1 = (strtotime($d1->format('d-m-Y H:i:s'))*1000)-(strtotime($d2->format('d-m-Y H:i:s'))*1000);

echo "Value of s1 =  ".$s1;

Returning 60998000 value which is mismatching with return value of javascript

Please let me know where i am wrong.

CodePudding user response:

Your issue is that you are passing a timestamp to date but date requires an integer timestamp so will trim away all milliseconds and microseconds.

You can parse a timestamp with fractional time up to microsecond accuracy using DateTime::createFromFormat('U.u',$sec) as for example in:

date_default_timezone_set("Asia/Kolkata");   //India time (GMT 5:30)

$d1 = new DateTime("2022-1-13 00:00:00");

$mili = 1641951202187.3433;
$sec = $mili /1000;
$d2 = DateTime::createFromFormat('U.u',$sec);
$s1 = ($d1->getTimestamp()*1000)-($d2->format('U.u')*1000);

echo "Value of s1 =  ".$s1;

This will output 60997812.699951 and the discrepency is because (I think) because the last digit is beyond the accuracy of PHP so will be discarded.

Note: The format U.u stands for timestamp in seconds.fraction in microseconds and the microseconds fraction can be up to 6 digits. More details in the manual

CodePudding user response:

Try this
$d1 = new Date("2022-01-13 00:00:00");
$d2 = new Date();
$d2->setTime(1641951202187.3433);  

echo $d1->diff($d2)->format("%a"); // returning value 60997813
  • Related