在javascript中将时间戳转换为人类日期的函数 [英] Function to convert timestamp to human date in javascript

查看:28
本文介绍了在javascript中将时间戳转换为人类日期的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用javascript中的函数将此时间戳1382086394000转换为2013-10-18 08:53:14?目前我有这个功能:

How to convert this timestamp 1382086394000 to 2013-10-18 08:53:14 using a function in javascript? Currently I have this function:

function cleanDate(d) {return new Date(+d.replace(//Date((d+))//, '$1'));}

推荐答案

1382086394000 的值可能是一个时间值,它是自 1970-01-01T00:00:00Z 以来的毫秒数.您可以使用 Date 构造函数:

The value 1382086394000 is probably a time value, which is the number of milliseconds since 1970-01-01T00:00:00Z. You can use it to create an ECMAScript Date object using the Date constructor:

var d = new Date(1382086394000);

如何将其转换为可读的内容取决于您.简单地将它发送到输出应该调用内部 (并且完全依赖于实现) toString 方法*,该方法通常以人类可读的方式打印等效的系统时间形式,例如

How you convert that into something readable is up to you. Simply sending it to output should call the internal (and entirely implementation dependent) toString method* that usually prints the equivalent system time in a human readable form, e.g.

Fri Oct 18 2013 18:53:14 GMT+1000 (EST) 

在 ES5 中还有一些其他的内置格式选项:

In ES5 there are some other built-in formatting options:

等等.请注意,大多数都依赖于实现,并且在不同的浏览器中会有所不同.如果您希望在所有浏览器中使用相同的格式,则需要自己格式化日期,例如:

and so on. Note that most are implementation dependent and will be different in different browsers. If you want the same format across all browsers, you'll need to format the date yourself, e.g.:

alert(d.getDate() + '/' + (d.getMonth()+1) + '/' + d.getFullYear());

* Date.prototype.toString 的格式已经在 ECMAScript 2018.它可能需要一段时间才能在所有实现中无处不在,但至少现在更常见的浏览器都支持它.

* The format of Date.prototype.toString has been standardised in ECMAScript 2018. It might be a while before it's ubiquitous across all implementations, but at least the more common browsers support it now.

这篇关于在javascript中将时间戳转换为人类日期的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆