如何从UTC字符串获取小时和分钟?

问题描述 投票:0回答:2

我想将日期时间从本地时间转换为UTC格式,然后将该UTC时间解码回我的原始本地时间。

将本地时间转换为UTC,我使用了下面的代码,效果很好。

const now = new Date();    
let d = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate(), 13, 5, 0);
console.log(new Date(d).getHours(), new Date(d).getMinutes());

上面的代码为我提供了+5:30的UTC时间,输出为18,35(18:35:00)

这里,我将下面的代码转换回18,35(18:35:00)到13:05:00

const now = new Date();
let d = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 18, 35, 0);
console.log(d.toUTCString());

上面的代码为我提供了一个字符串格式的日期,该日期的时间为13:05:00是适当的。

现在,我想从该日期字符串中获取小时和分钟。

我尝试添加:

new Date(d.UTCString()) 

但是,它为我提供了18小时和35分钟,而我希望13小时和05分钟。请帮我解决一下这个。谢谢。

javascript date
2个回答
1
投票

解决方案:

  1. 使用setHours()setMinutes() JS日期功能设置小时和分钟
  2. 使用getHours()getMintues() JS日期函数获取小时和分钟

注意:现在日期基于用户的当前时间。

const now = new Date();
now.setHours(15);
now.setMinutes(30);

console.log(now.toString());
console.log(now.getMinutes());
console.log(now.getMinutes());

更多了解时间的资源:digtialocean.com


1
投票

这里是toLocaleTimeString方法

toLocaleTimeString
© www.soinside.com 2019 - 2024. All rights reserved.