【发布时间】:2021-03-26 11:44:11
【问题描述】:
对于特定的应用程序,我需要将我的日期格式从
2021 年 3 月 26 日星期五 16:00:01 GMT+0400(海湾标准时间)
到
2023 年 1 月 1 日 00:00:00 GMT+03:00
我该怎么做?
【问题讨论】:
标签: javascript date format
对于特定的应用程序,我需要将我的日期格式从
2021 年 3 月 26 日星期五 16:00:01 GMT+0400(海湾标准时间)
到
2023 年 1 月 1 日 00:00:00 GMT+03:00
我该怎么做?
【问题讨论】:
标签: javascript date format
这就是我解决格式问题的方法:
//1. Get closing time from event
time = new Date(item.returnValues['closingTime'] * 1000);
//2. Formatting the date for the date counter input
const options = { year: 'numeric', month: 'long', day: 'numeric' };
firstPart= time.toLocaleDateString('en-US', options);
//3. Get original GMT time from the var time
secondPart = time.toString().slice(15, 24);
secondPart = secondPart.concat(" GMT+04:00 ");
//4. concat the two strings into the desired form
ct = firstPart.concat(secondPart);
【讨论】:
基于mozila's documents,当时间要显示为字符串时,前三个字母总是代表工作日名称,它们将与其他数据用一个空格分开,所以我们可以省略前4个字符(来自最终字符串的 3 个首字母 + 后跟空格),函数如下:
let sampleDate = Date();
function sliceDayFromTime(dateTime) {
return dateTime.slice(4);
}
console.log(sliceDayFromTime(sampleDate));
为了使用更高级的格式,您可以使用Intl.DateTimeFormat,这是一个启用语言敏感的日期和时间格式的对象。
对于你上面提到的具体例子,我相信下面的代码很有用
var sampleDate = new Date();
var formatter = new Intl.DateTimeFormat('en-us', {
month: 'long',
year: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
hour12: false,
timeZoneName: 'short'
});
function minimalFormatDate(date) {
return formatter.format(date);
}
function advancedFromatDate(date) {
return formatter.formatToParts(date).map(({type, value}, index) => {
if (type === 'literal' && index === 5) {
return ' '
}
return value;
}).join('');
}
console.log('minimal formating example: ', minimalFormatDate(sampleDate));
console.log('advanced formating example: ', advancedFromatDate(sampleDate));
【讨论】: