javascript - 将 DOMTimeStamp 转换为本地化 HH :MM:SS MM-DD-YY via Javascript

标签 javascript geolocation w3c

W3C Geolocation API (除其他外)使用 DOMTimeStamp因为它的修复时间。

这是“自 Unix 纪元开始以来的毫秒数”。

将其转换为人类可读格式并针对本地时区进行调整的最简单方法是什么?

最佳答案

Date 的一个版本构造函数将“自 Unix 纪元开始以来的毫秒数”作为其第一个也是唯一的参数。

假设您的时间戳在一个名为 domTimeStamp 的变量中,下面的代码会将此时间戳转换为本地时间(假设用户在她/他的机器上设置了正确的日期和时区)并打印出人类可读的日期版本:

var d = new Date(domTimeStamp);
document.write(d.toLocaleString());

其他内置日期格式化方法包括:
Date.toDateString()
Date.toLocaleDateString()
Date.toLocaleTimeString()
Date.toString()
Date.toTimeString()
Date.toUTCString()

假设您的要求是打印“HH:MM:SS MM-DD-YY”的确切模式,您可以执行以下操作:
var d = new Date(domTimeStamp);
var hours = d.getHours(),
    minutes = d.getMinutes(),
    seconds = d.getSeconds(),
    month = d.getMonth() + 1,
    day = d.getDate(),
    year = d.getFullYear() % 100;

function pad(d) {
    return (d < 10 ? "0" : "") + d;
}

var formattedDate = pad(hours) + ":"
                  + pad(minutes) + ":"
                  + pad(seconds) + " "
                  + pad(month) + "-"
                  + pad(day) + "-"
                  + pad(year);

document.write(formattedDate);

关于javascript - 将 DOMTimeStamp 转换为本地化 HH :MM:SS MM-DD-YY via Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3089308/

相关文章:

javascript - Document.importNode VS Node.cloneNode(实例)

html - 验证错误 "Bad value apple-touch-icon-precomposed for attribute rel on element link: Keyword apple-touch-icon-precomposed is not registered."

javascript - 从不同的命名空间加入命名空间房间

javascript - undefined variable 作为函数参数 javascript

javascript - Javascript 中的面向对象编程

ios - 如何在用户行走时跟踪 GPS 坐标,来自 ios 平台的 xamarin.forms

SQL Server 计算两组纬度/经度列之间的距离

python - 使用 Python 计算多边形形状文件中的点数

php - 使用 Json 传递两个查询

java - 将 dom4j 文档转换为 W3c 文档