如何将JavaScript的Date对象格式化为字符串?(最好的格式是:10-Aug-2010)
如果有人正在寻找一种非常简单的ES6解决方案进行复制、粘贴和采用:
const dateToString = d => `${d.getFullYear()}-${('00' + (d.getMonth() + 1)).slice(-2)}-${('00' + d.getDate()).slice(-2)}`
// how to use:
const myDate = new Date(Date.parse('04 Dec 1995 00:12:00 GMT'))
console.log(dateToString(myDate)) // 1995-12-04
('0' + oneOrTwoDigitNumber).slice(-2)
。无需使用('00' + oneOrTwoDigitNumber).slice(-2)
,因为我们知道oneOrTwoDigitNumber至少有一位数字。 - David J.截至2019年,似乎可以使用toLocaleDateString仅返回特定部分,然后按照需要进行拼接:
var date = new Date();
console.log(date.toLocaleDateString("en-US", { day: 'numeric' })
+ "-"+ date.toLocaleDateString("en-US", { month: 'short' })
+ "-" + date.toLocaleDateString("en-US", { year: 'numeric' }) );
> 16-Nov-2019
console.log(date.toLocaleDateString("en-US", { month: 'long' })
+ " " + date.toLocaleDateString("en-US", { day: 'numeric' })
+ ", " + date.toLocaleDateString("en-US", { year: 'numeric' }) );
> November 16, 2019
10-Aug-2010
,您可以使用.toDateString()
和ES6数组解构。const formattedDate = new Date().toDateString()
// The above yields e.g. 'Mon Jan 06 2020'
const [, month, day, year] = formattedDate.split(' ')
const ddMmmYyyy = `${day}-${month}-${year}`
// or
const ddMmmYyyy = [day, month, year].join('-')
下面是文档中的示例:
Date.create().format('{Weekday} {Month} {dd}, {yyyy}');
Date.create().format('{12hr}:{mm}{tt}')
在这个答案中,我发展了JD Smith的想法。我能够缩短JD Smith正则表达式。
let format= d=> d.toString().replace(/\w+ (\w+) (\d+) (\d+).*/,'$2-$1-$3');
console.log( format(Date()) );
Dave也基于JD Smith的想法,但他避免了正则表达式并给出了一个非常好的解决方案 - 我稍微修改了他的解决方案(通过改变split参数)并将其包装在一个包装器中。
let format= (d,a=d.toString().split` `)=> a[2]+"-"+a[1]+"-"+a[3];
console.log( format(Date()) );
你可以简单地这样做:
let date = new Date().toLocaleDateString('en-us',{day: 'numeric'})
let month = new Date().toLocaleDateString('en-us',{month: 'long'})
let year = new Date().toLocaleDateString('en-us',{year: 'numeric'})
const FormattedDate = `${date}-${month}-${year}`
console.log(FormattedDate) // 26-March-2022
Javascript的Intl.DateTimeFormat
方法为日期格式化提供了一种便捷的方式。
以下是如何构建所需格式:
const date = new Date("2010-08-10");
let d=new Intl.DateTimeFormat('en-GB',{year:"numeric", month:"short",day:"2-digit"}).format(date).split(" ").join("-");
console.log(d);
要获得“10-Aug-2010”,请尝试:
var date = new Date('2010-08-10 00:00:00');
date = date.toLocaleDateString(undefined, {day:'2-digit'}) + '-' + date.toLocaleDateString(undefined, {month:'short'}) + '-' + date.toLocaleDateString(undefined, {year:'numeric'})
关于浏览器支持,请查看toLocaleDateString。
试试这个:
function init(){
var d = new Date();
var day = d.getDate();
var x = d.toDateString().substr(4, 3);
var year = d.getFullYear();
document.querySelector("#mydate").innerHTML = day + '-' + x + '-' + year;
}
window.onload = init;
<div id="mydate"></div>
DateFormatter.formatDate(new Date(2010,7,10), 'DD-MMM-YYYY')
=>2010年8月10日
DateFormatter.formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss')
=>2017年11月22日 19:52:37
DateFormatter.formatDate(new Date(2005, 1, 2, 3, 4, 5), 'D DD DDD DDDD, M MM MMM MMMM, YY YYYY, h hh H HH, m mm, s ss, a A')
=>2 02 星期三 二月 February, 05 2005, 3 03 3 03, 4 04, 5 05, 上午 AM
var DateFormatter = {
monthNames: [
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
],
dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
formatDate: function (date, format) {
var self = this;
format = self.getProperDigits(format, /d+/gi, date.getDate());
format = self.getProperDigits(format, /M+/g, date.getMonth() + 1);
format = format.replace(/y+/gi, function (y) {
var len = y.length;
var year = date.getFullYear();
if (len == 2)
return (year + "").slice(-2);
else if (len == 4)
return year;
return y;
})
format = self.getProperDigits(format, /H+/g, date.getHours());
format = self.getProperDigits(format, /h+/g, self.getHours12(date.getHours()));
format = self.getProperDigits(format, /m+/g, date.getMinutes());
format = self.getProperDigits(format, /s+/gi, date.getSeconds());
format = format.replace(/a/ig, function (a) {
var amPm = self.getAmPm(date.getHours())
if (a === 'A')
return amPm.toUpperCase();
return amPm;
})
format = self.getFullOr3Letters(format, /d+/gi, self.dayNames, date.getDay())
format = self.getFullOr3Letters(format, /M+/g, self.monthNames, date.getMonth())
return format;
},
getProperDigits: function (format, regex, value) {
return format.replace(regex, function (m) {
var length = m.length;
if (length == 1)
return value;
else if (length == 2)
return ('0' + value).slice(-2);
return m;
})
},
getHours12: function (hours) {
// https://dev59.com/qGkv5IYBdhLWcg3wfA4P
return (hours + 24) % 12 || 12;
},
getAmPm: function (hours) {
// https://dev59.com/-Gox5IYBdhLWcg3w6oj0
return hours >= 12 ? 'pm' : 'am';
},
getFullOr3Letters: function (format, regex, nameArray, value) {
return format.replace(regex, function (s) {
var len = s.length;
if (len == 3)
return nameArray[value].substr(0, 3);
else if (len == 4)
return nameArray[value];
return s;
})
}
}
console.log(DateFormatter.formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss'));
console.log(DateFormatter.formatDate(new Date(), 'D DD DDD DDDD, M MM MMM MMMM, YY YYYY, h hh H HH, m mm, s ss, a A'));
console.log(DateFormatter.formatDate(new Date(2005, 1, 2, 3, 4, 5), 'D DD DDD DDDD, M MM MMM MMMM, YY YYYY, h hh H HH, m mm, s ss, a A'));
Z
,UTC时区偏移)。
未经彻底测试
myDate.getDay()
并不返回一周中的星期几,而是返回星期几在这周中的位置。myDate.getDate()
返回的是当前日期的星期几。 - JimenemextoLocaleDateString
。 - onmyway133