如何将JavaScript的Date对象格式化为字符串?(最好的格式是:10-Aug-2010)
如果你想要一个简短易懂的函数,可以根据自己的需求进行调整。
timeStamp参数是从1970年开始计算的毫秒数 - 它可以通过new Date().getTime()
以及其他许多设备来获取...
好吧,我改变了主意。我增加了一个额外的函数来进行零填充。可恶!
function zeroPad(aNumber) {
return ("0"+aNumber).slice(-2);
}
function humanTime(timeStamp) {
var M = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var D = new Date(timeStamp); // 23 Aug 2016 16:45:59 <-- Desired format.
return D.getDate() + " " + M[D.getMonth()] + " " + D.getFullYear() + " " + D.getHours() + ":" + zeroPad(d.getMinutes()) + ":" + zeroPad(D.getSeconds());
}
var dtFormat = require('dtformat');
var today = new Date();
dtFormat(today, "dddd, mmmm dS, yyyy, h:MM:ss TT");
var now = new Date()
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
var formattedDate = now.getDate() + "-" + months[now.getMonth()] + "-" + now.getFullYear()
alert(formattedDate)
简短、广泛兼容的方法:
function formatDate(date) {
date.toISOString()
.replace(/^(\d+)-(\d+)-(\d+).*$/, // Only extract Y-M-D
function (a,y,m,d) {
return [
d, // Day
['Jan','Feb','Mar','Apr','May','Jun', // Month Names
'Jul','Ago','Sep','Oct','Nov','Dec']
[m-1], // Month
y // Year
].join('-') // Stitch together
})
}
date.toISOString().replace(/^(\d+)-(\d+)-(\d+)T(\d+):(\d+):(\d+).(\d+)Z$/, function (a,y,m,d) {return [d,['Jan','Feb','Mar','Apr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic'][m-1],y].join('-')})
var date = new Date();
Ext.Date.format(date, "d-M-Y");
"11-Nov-2015"
您可以使用其他方式格式化日期:
function formatDate(dDate,sMode){
var today = dDate;
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd = '0'+dd
}
if(mm<10) {
mm = '0'+mm
}
if (sMode+""==""){
sMode = "dd/mm/yyyy";
}
if (sMode == "yyyy-mm-dd"){
return yyyy + "-" + mm + "-" + dd + "";
}
if (sMode == "dd/mm/yyyy"){
return dd + "/" + mm + "/" + yyyy;
}
}
new Date('2015-1-1').to('dd.MM.yy') // Outputs 01.01.2015
"2015-01-01T10:11:12.123Z".to('dd.MM.yy') // Outputs 01.01.2015
本地化文件(smarti.to.{culture}.js)中还定义了自定义短模式。例如(smarti.to.et-EE.js):
new Date('2015-1-1').to('d') // Outputs 1.01.2015
同时,它还具备多种格式化能力:
smarti.format('{0:n2} + {1:n2} = {2:n2}', 1, 2, 3) // Output: 1,00 + 2,00 = 3,00
yy
= 两位数年份;
yyyy
= 完整的年份
M
= 数字月份;
MM
= 两位数字月份;
MMM
= 简写月份名称;
MMMM
= 完整的月份名称
EEEE
= 完整的星期几名称;
EEE
= 简写星期几名称
d
= 数字日期;
dd
= 两位数字日期
h
= 小时;
hh
= 两位数字小时
m
= 分钟;
mm
= 两位数字分钟
s
= 秒;
ss
= 两位数字秒
S
= 毫秒
与SimpleDateFormat类(Java)使用相似的格式化形式。
var monthNames = [
"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"
];
var dayOfWeekNames = [
"Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday"
];
function formatDate(date, formatStr){
if (!formatStr) {
formatStr = 'dd/mm/yyyy';
}
var day = date.getDate(),
month = date.getMonth(),
year = date.getFullYear(),
hour = date.getHours(),
minute = date.getMinutes(),
second = date.getSeconds(),
miliseconds = date.getMilliseconds(),
hh = twoDigitPad(hour),
mm = twoDigitPad(minute),
ss = twoDigitPad(second),
EEEE = dayOfWeekNames[date.getDay()],
EEE = EEEE.substr(0, 3),
dd = twoDigitPad(day),
M = month + 1,
MM = twoDigitPad(M),
MMMM = monthNames[month],
MMM = MMMM.substr(0, 3),
yyyy = year + "",
yy = yyyy.substr(2, 2)
;
return formatStr
.replace('hh', hh).replace('h', hour)
.replace('mm', mm).replace('m', minute)
.replace('ss', ss).replace('s', second)
.replace('S', miliseconds)
.replace('dd', dd).replace('d', day)
.replace('MMMM', MMMM).replace('MMM', MMM).replace('MM', MM).replace('M', M)
.replace('EEEE', EEEE).replace('EEE', EEE)
.replace('yyyy', yyyy)
.replace('yy', yy)
;
}
function twoDigitPad(num) {
return num < 10 ? "0" + num : num;
}
console.log(formatDate(new Date()));
console.log(formatDate(new Date(), 'EEEE, MMMM d, yyyy hh:mm:ss:S'));
console.log(formatDate(new Date(), 'EEE, MMM d, yyyy hh:mm'));
console.log(formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss:S'));
console.log(formatDate(new Date(), 'yy-MM-dd hh:mm'));
在我的案例中,我已经将日期格式从'01/07/2022'转换为'2022-07-01'
const formatDate = date => {
const d = new Date(date)
let month = (d.getMonth() + 1).toString()
let day = d.getDate().toString()
const year = d.getFullYear()
if (month.length < 2) {
month = '0' + month
}
if (day.length < 2) {
day = '0' + day
}
return [ year, month, day ].join('-')
}
console.log(formatDate('01/07/2022'))
使用此过程
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec']
const date = new Date()
const dateString = `${date.getDate()}-${MONTHS[date.getMonth()]}-${date.getFullYear()}`
console.log(dateString)
这是主要答案的修改版本,将月份改为3个字符,年份改为2位数字:
function formatDate(date) {
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var day = date.getDate(), monthIndex = date.getMonth(), year = date.getFullYear().toString().substr(-2);
return day + ' ' + monthNames[monthIndex] + ' ' + year;
}
document.write(formatDate(new Date()));
myDate.getDay()
并不返回一周中的星期几,而是返回星期几在这周中的位置。myDate.getDate()
返回的是当前日期的星期几。 - JimenemextoLocaleDateString
。 - onmyway133