我想将一串日期“2018年8月19日”转换为“mm-dd-yyyy”格式(不使用moment.js)我用过
d = new Date("Aug 19th 2018")
它导致NaN无法解析“19”。怎么做到这一点?
创建自定义函数并将日期转换为所需格式
let dt = "Aug 19th 2018";
function convertDate(dt) {
let newFormat = "";
// a mapping of month name and numerical value
let monthMapping = {
jan:'01',
feb: '02',
mar: '03',
april: '04',
may: '05',
june: '06',
july: '07',
aug: '08',
sept: '09',
oct: '10',
nov: '11',
dec: '12'
}
// split the input string into three pieces
let splitDt = dt.split(" ");
// from the first piece get the numerical month value from the above obhect
let getMonth = monthMapping[splitDt[0].toLowerCase()];
let date = parseInt(splitDt[1], 10)
let year = splitDt[2]
return `${getMonth}-${date}-${year}`
}
console.log(convertDate(dt))
您可以split()
字符串,使用该对象获取月份索引并使用parseInt()
从当天提取数字。
使用new Date(year, monthIndex , day)
获取日期对象。
let formatDate = s => {
let months = {jan:'0',feb:'1',mar:'2',apr:'3', may:'4',jun:'5',jul:'6',aug:'7',sep:'8',oct:'9',nov:'10',dec:'11'};
let [m, d, y] = s.split(' ');
return new Date(y, months[m.toLowerCase()], parseInt(d));
};
var date1 = formatDate("Aug 19th 2018");
var date2 = formatDate("Mar 19th 2000");
Doc:new Date()
您可以使用正则表达式替换日期值中的所有字母,然后再将该字符串传递给Date()构造函数
var dateString = "AUG 19th 2018";
var dateFrag = dateString.split(' ');
dateFrag[1] = dateFrag[1].replace(/[a-zA-Z]/g,'');
var d = new Date(dateFrag);
console.log(d);
@Saurin Vala的解决方案有一个问题,就像当时js doc说的那样,在解析字符串时,必须给出一种格式,否则它将构建js Date(),这可能不适用于某些浏览器take a look at the issue on moment js doc。正确的方式就是这样
var a = moment("Aug 19th 2018", 'MMM Do YYYY')
现在你可以通过多种方式输出格式了
更新你可以先取代'th','rd'
var mydate= new Date(ReturnProperDate("Aug 19th 2018"));
//you can create manual function to handle format now
console.log( (1+mydate.getMonth()) +"-"+ mydate.getDate()+"-" + mydate.getFullYear());
function ReturnProperDate(date){
date=date.replace('th','');
date=date.replace('rd','');
date=date.replace('xx',''); //if any other
return date;
}
使用时刻js:https://momentjs.com/
那么你可以轻松地在你渴望的合成中获得约会
moment(yourDate).format('DD-MMM-YYYY'); // put format as you want
moment().format('MMMM Do YYYY, h:mm:ss a'); // June 28th 2018, 9:58:10 am
尝试String.replace():
var str='Aug 19th 2018'.replace(/(\w{3})\s(\d{1,})\w{2}\s(\d{4})/,function(match,m,d,y){
return ({'Jan':'01','Feb':'02','Mar':'03','Apr':'04','May':'05','Jun':'06','Jul':'07','Aug':'08','Sep':'09','Oct':'10','Nov':'11','Dec':'12'})[m]+'-'+d+'/'+y;
});
console.log(str);