简体   繁体   English

将PHP Unix时间戳转换为Javascript时间戳格式

[英]Convert PHP Unix Timestamp to Javascript Timestamp format

I'm throwing a unix timestamp from my php to my javascript and I noticed that PHP and Javascript timestamps are different (seconds vs. milliseconds) from the epoch. 我在我的php和javascript中抛出了一个unix时间戳,并且我注意到PHP和Javascript时间戳与时代不同(秒数与毫秒数)。

What I'm basically doing is to echo the php unixtime then add 3 zeroes (as to simply multiply it by 1000) but I noticed that when I check it, it shows that the time is off by around 4-8 hours. 我基本上在做的是回显php unixtime,然后添加3个零(将其简单地乘以1000),但是我注意到当我检查它时,它表明时间大约减少了4-8小时。

I am using canvas.js and I need to convert it using the unix timestamp 我正在使用canvas.js,我需要使用unix时间戳对其进行转换

For example: 例如:

1434183780 1434183780

Jun 13 2015 8:23AM 2015年6月13日8:23 AM

I add 3 zeroes 我加三个零

1434183780000 1434183780000

echo "{ x:".$chartData[$loop]['time']."000 , y:1 }";

and what happens is the time becomes: 时间将变成:

Jun 13 2015 16:23PM 2015年6月13日16:23 PM

Everything is working fine except that the time becomes completely distorted. 一切工作正常,除了时间变得完全失真。

How could I make it work without the time being changed once I put it on javascript? 一旦将其放在javascript上,如何在不更改时间的情况下使它工作? I'd prefer to keep it in unixtime as I still use it in that format when I do something else with it. 我宁愿将其保留在unixtime中,因为当我对它进行其他操作时,我仍然以该格式使用它。

This sounds just like a time zone issue. 这听起来像是时区问题。

A Unix timestamp is always a point in time in UTC . Unix时间戳始终是UTC的时间点。

When displaying it in a format like "Jun 13 2015 8:23AM" you are always using a certain time zone to display it as such. 以“ Jun 13 2015 8:23 AM”之类的格式显示它时,您总是使用特定时区来显示它。 The reason the time is being displayed as "16:23PM" is because a time zone other than you expect is being used to display the Unix timestamp. 时间显示为“ 16:23 PM”的原因是因为使用了非您期望的时区来显示Unix时间戳。

So the solution is simply making sure you're picking the correct time zone when displaying the timestamp. 因此,解决方案只是确保在显示时间戳时选择正确的时区。

If you're using the JavaScript Date object and you mean to use UTC, you can try using a method like toUTCString() : 如果您使用的是JavaScript Date对象,并且打算使用UTC,则可以尝试使用类似toUTCString()的方法:

console.log(new Date(1434183780000).toUTCString());
// Output: Sat, 13 Jun 2015 08:23:00 GMT

Date supports only the local time zone or UTC. Date仅支持本地时区或UTC。 If you want to construct your own formatted string in UTC, you can use the methods in Date starting with getUTC*() , like getUTCHours() or getUTCDate() . 如果要在UTC中构造自己的格式化字符串,则可以使用以getUTC*()开头的Date的方法,例如getUTCHours()getUTCDate()

See more info on the Date object in: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date 在以下网址中查看有关Date对象的更多信息: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM