Home > Enterprise >  How to convert time correctly in php?
How to convert time correctly in php?

Time:02-05

I have a time array like

[2023,1,3,17,0,0] 

When I use Date.UTC in javascript, It produces the right result

My code

const utcDate1 = new Date(Date.UTC(2023, 1, 3, 17,0,0));
console.log(utcDate1.toUTCString());

result:

"Fri, 03 Feb 2023 17:00:00 GMT"

How to get the same result in php like javascript ? i tried with mktime in php but the return result is not what i expected it to be different when using date.Utc in java script my php code

echo date("d-m-Y H:i:s",mktime(17,0,0,1,3,2023));

result by PHP :

03-01-2023 17:00:00

CodePudding user response:

Javascript uses a date format that stores months 0 based: month "0" means January.

PHP does not, php considers January to be month 1.

Thats why in js Date.UTC(2023, 1, 3, 17,0,0) represents February 3rd, but in php mktime(17,0,0,1,3,2023) represents January 3rd.

When using that js-style date input [2023,1,3,17,0,0] in php you'll have to 1 to the month value.


If that part of your system is under your control and you have the possibility to change the format you use to exchange date values between js and php, i'd highly recommend to use a format that both systems understand. E.g. ISO 8601 or unix timestamps.

  • Related