2

I want to display a UTC date using this JavaScriptcode on my webpage.

<script>
    function myDate()
    {
    var now = new Date();
    var d = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
    var x = document.getElementById("demo");
    x.innerHTML=d;
    }
</script>

With this code I am getting UTC date displayed as a local string as follows: "Thu Jul 04 2013 00:00:00 GMT+0530 (India Standard Time)"

I do not want display the string with a local time offset (GMT+0530 (IST)), instead I want the time to appear as UTC string format

4

3 回答 3

2

不同浏览器返回的日期格式不同

要从日期中删除 GMT OFFSET,您可以使用替换

var d = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
d = d.toString().replace(/GMT.+/,"");
于 2013-07-04T03:23:09.140 回答
1

首先,问题是您通过传入 UTC 年、月和日来实例化本地 Date 对象。然后使用提供的值创建一个本地日期。通过这样做,您可能会根据您希望它是 UTC 还是本地日期来创建不正确的日期。在您的情况下,如果您想var now使用 UTC,那么您当前实例化的方式与本地时间一样不正确。

无论如何,日期在 JavaScript 中可能很棘手,所以我会考虑为此使用Moment.js

这是一个很棒的库,它提供了您可能需要的所有用于操作和转换 JavaScript 日期的函数。

例如,使用 moment 您可以执行以下操作:

var now = moment(); // current date and time in local format
var nowAsUTC = now.utc(); // current local date and time converted to UTC
var alsoNowAsUTC = moment.utc() // same as the line above, but staring in UTC
console.log(nowUTC.format("DD/MM/YYYY, hh:mm:ss"))// prints a pretty UTC string
于 2013-07-04T03:06:48.810 回答
0

嗯.. 你确定要显示 UTC-8 吗?我猜你真的想将时间转换为美国太平洋时区。这并不总是UTC-8。有时是 UTC-8,有时是 UTC-7。

如果您实际上不在美国太平洋时区,那么在 JavaScript 中可靠地执行此操作的唯一方法是使用实​​现 TZDB 数据库的库。 我在这里列出了其中的几个

例如,使用walltime-js库,您可以执行以下操作:

var date = new Date();
var pacific = WallTime.UTCToWallTime(date, "America/Los_Angeles");
var s = pacific.toDateString() + ' ' + pacific.toFormattedTime();

// output:  "Fri Apr 26 2013 5:44 PM"

您不能只添加或减去一个固定数字,因为目标时区可能使用不同的偏移量,具体取决于您所谈论的日期。这主要是由于夏令时,但也因为时区随时间而变化。

于 2013-07-06T21:57:02.707 回答