本文由我司收集整编,推荐下载,如有疑问,请与我司联系
JavaScript
JavaScript - 将时间戳转换为日期,然后转换回时间戳[英]JavaScript - convert timestamp to date, then convert back to timestamp My server app returns a timestamp
string which is in UTC.
我的服务器应用程序返回一个 UTC 时间戳字符串。
Now I want to convert it to a date object to get the local datetime, then convert that date
object back to timestamp to get the local timestamp.
现在我想将它转换为日期对象以获取本地日期时间,然后将该日期对象转换回时间 戳以获取本地时间戳。
This doesn’t seem to work as both strings outputted are identical 这似乎不起作用,因为输出的两个字符串是相同的
console.log(JSON.stringify(timestamp));var
date
=
new
Date(timestamp*1000).getTime();console.log(JSON.stringify(date)); How do I work this out?
我该如何解决这个问题? 0
You need to create a new instance of Date using the timestamp (which I assume is
already a well-formatted date-object). Your code will look like this:
您需要使用时间戳创建一个新的 Date 实例(我假设它已经是格式良好的日期对 象)。您的代码将如下所示:
console.log(JSON.stringify(timestamp));var
date
=
new
Date(timestamp);console.log(JSON.stringify(date)); Give it a try and let me know if the output is still the same.
尝试一下,让我知道输出是否仍然相同。 0
I think this is what u need. You need to take the current time, convert it and send it back
本文由我司收集整编,推荐下载,如有疑问,请与我司联系
to the server in the format u need.
我想这就是你需要的。您需要获取当前时间,转换它并以您需要的格式将其发送回 服务器。
var timestamp = 1470621520;console.log(JSON.stringify(timestamp));var date = Math.floor((new Date()).getTime() / 1000);console.log(JSON.stringify(date)); EDIT As per the comments, for converting the UTC time to local timezone you could do, 编辑根据评论,您可以将 UTC 时间转换为本地时区,
var utcDate = 1470621520;var localDate = new Date(utcDate);console.log(localDate); This will automatically take care of the UTC to local time zone conversion. 这将自动处理 UTC 到本地时区转换。
tips:感谢大家的阅读,本文由我司收集整编。仅供参阅!
相关推荐: