通过 Javascript 将 DOMTimeStamp 转换为本地化的 HH:MM:SS MM-DD-YY

Converting DOMTimeStamp to localized HH:MM:SS MM-DD-YY via Javascript(通过 Javascript 将 DOMTimeStamp 转换为本地化的 HH:MM:SS MM-DD-YY)
本文介绍了通过 Javascript 将 DOMTimeStamp 转换为本地化的 HH:MM:SS MM-DD-YY的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

W3C Geolocation API(以及其他)使用 DOMTimeStamp修复.

The W3C Geolocation API (among others) uses DOMTimeStamp for its time-of-fix.

这是自 Unix 纪元开始以来的毫秒数".

This is "milliseconds since the start of the Unix Epoch".

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

What's the easiest way to convert this into a human readable format and adjust for the local timezone?

推荐答案

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

One version of the Date constructor takes the number of "milliseconds since the start of the Unix Epoch" as its first and only parameter.

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

Assuming your timestamp is in a variable called domTimeStamp, the following code will convert this timestamp to local time (assuming the user has the correct date and timezone set on her/his machine) and print a human-readable version of the date:

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

其他内置日期格式化方法包括:

Other built-in date-formatting methods include:

Date.toDateString()
Date.toLocaleDateString()
Date.toLocaleTimeString()
Date.toString()
Date.toTimeString()
Date.toUTCString()

假设您的要求是打印HH:MM:SS MM-DD-YY"的确切模式,您可以执行以下操作:

Assuming your requirement is to print the exact pattern of "HH:MM:SS MM-DD-YY", you could do something like this:

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

SCRIPT5: Access is denied in IE9 on xmlhttprequest(SCRIPT5:在 IE9 中对 xmlhttprequest 的访问被拒绝)
XMLHttpRequest module not defined/found(XMLHttpRequest 模块未定义/未找到)
Show a progress bar for downloading files using XHR2/AJAX(显示使用 XHR2/AJAX 下载文件的进度条)
How can I open a JSON file in JavaScript without jQuery?(如何在没有 jQuery 的情况下在 JavaScript 中打开 JSON 文件?)
quot;Origin null is not allowed by Access-Control-Allow-Originquot; in Chrome. Why?(“Access-Control-Allow-Origin 不允许 Origin null在铬.为什么?)
How to get response url in XMLHttpRequest?(如何在 XMLHttpRequest 中获取响应 url?)