我需要将我的日期和时间转换为UTC /通用时间戳,而且我不确定如何转换它(我在美国东部时间工作)。我需要这种格式:YYYY-MM-DD HH:mm:我已经使用这段代码构建的ss:
var now = new Date();
var year = "" + now.getFullYear();
var month = "" + (now.getMonth() + 1);
if (month.length == 1) {
month = "0" + month;
}
day = "" + now.getDate();
if (day.length == 1) {
day = "0" + day;
}
hour = "" + now.getHours();
if (hour.length == 1) {
hour = "0" + hour;
}
minute = "" + now.getMinutes();
if (minute.length == 1) {
minute = "0" + minute;
}
second = "" + now.getSeconds();
if (second.length == 1) {
second = "0" + second;
}
var timeStamp = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
返回类似" 2017-05-19 16:23:19"如果可能的话,我们如何将其转换为UTC?谢谢你的帮助。
答案 0 :(得分:0)
在代码中 首先创建一个javascript日期对象,这里是调用
new Date(year, month[, date[, hours[, minutes[, seconds[, milliseconds]]]]]);
然后
var isoDate = new Date('yourdatehere').toISOString();
所以对你来说就是
var date = new Date(year, month, day, hour, minute, second, 0);
var isoDate = date.toISOString();
小提琴我试图这样做。也许这就是你想要的方式
答案 1 :(得分:0)
这是一种方法:
var timestamp = "2017-05-19 16:23:19"; //substitute by your timestamp variable
var date = new Date(timestamp.replace(' ', 'T') + 'Z');
var strUDate = date.toISOString();
console.log(strUDate);
答案 2 :(得分:0)
在Javascript new Date()
中创建日期时,您的对象会存储创建UTC之前或之后的分钟数。您可以随时使用getTimezoneOffset()
方法
如果您希望将UTC时间作为字符串,则只能使用一种方法。
const date = new Date();
date.toUTCString();
// Fri, 19 May 2017 21:07:27 GMT
如果您希望以首选字符串格式使用它,则必须以与您相同的方式手动构建字符串。只需用UTC方法替换你的方法。
const date = new Date();
const year = "" + date.getUTCDate();
let month = "" + (date.getUTCMonth() + 1); // we add a 1 because month is 0 based
if (month.length == 1) {
month = "0" + month;
}
let day = "" + date.getUTCDate();
if (day.length == 1) {
day = "0" + day;
}
let hour = "" + date.getUTCHours();
if (hour.length == 1) {
hour = "0" + hour;
}
let minute = "" + date.getUTCMinutes();
if (minute.length == 1) {
minute = "0" + minute;
}
let second = "" + date.getUTCSeconds();
if (second.length == 1) {
second = "0" + second;
const timeStamp = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
如果你想要短手
const d = new Date();
const dateString = `${d.getUTCFullYear()}-${('0' + d.getUTCMonth()).slice(-2)}-${('0' + d.getUTCDate()).slice(-2)} ${('0' + d.getUTCHours()).slice(-2)}:${('0' + d.getUTCMinutes()).slice(-2)}:${('0' + d.getUTCSeconds()).slice(-2)}`;
// 2017-04-19 23:39:28