尝试搜索如何在JS中添加或修改.toLocaleTimeString的时间,因为该时间不适用于我一开始使用的计算。我有一个输出,可以让我离开用户位置几个小时(正数或负数),我希望将其添加到他们的实际时间中。
这就是我要根据-7(如“西7时”)或7(如“ 7时”)的输出来操作和添加/删除小时的方法:
var endTime = new Date(unixUserTime*1000);
endTime.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit', hour12: true});
我之前尝试过的事情:
var endTime = new Date(unixUserTime*1000);
// Hours part from the timestamp
var hours = Math.floor(endTime.getHours() + 3);
// Minutes part from the timestamp
var minutes = "0" + endTime.getMinutes();
// Seconds part from the timestamp
var seconds = "0" + endTime.getSeconds();
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
formattedTime.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit', hour12: true}); //This throws an error
我也尝试过转换,像这样:
var endTime = new Date(unixUserTime*1000).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit', hour12: true}); //This throws an error;
// Hours part from the timestamp
var hours = Math.floor(endTime.getHours() + 3);
// Minutes part from the timestamp
var minutes = "0" + endTime.getMinutes();
// Seconds part from the timestamp
var seconds = "0" + endTime.getSeconds();
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
formattedTime;
答案 0 :(得分:3)
我建议您使用moment.js
您可以轻松完成此操作而不会弄乱语言环境:
moment(date).add(7, 'hours')
// for offsets
moment(date).utcOffset(60)
moment(date).utcOffset('+0100')