我有一个日期,格式是2014年5月11日太阳。如何使用JavaScript将其转换为2014-05-11 ?
函数taskDate(dateMilli) {
var d = (new Date(dateMilli) + ")。分割(' ');
D [2] = D [2] + ',';
返回[d[0], d[1], d[2], d[3]]。加入(' ');
}
var datemilli =日期。解析(' 2014年5月11日');
console.log (taskDate (datemilli));
上面的代码给了我相同的日期格式,2014年5月11日。我该如何解决这个问题?
之前的一些答案是可以的,但是不是很灵活。我想要一些能够真正处理更多边缘情况的东西,所以我采用了@orangleliu的答案并扩展了它。https://jsfiddle.net/8904cmLd/1/
function DateToString(inDate, formatString) {
// Written by m1m1k 2018-04-05
// Validate that we're working with a date
if(!isValidDate(inDate))
{
inDate = new Date(inDate);
}
// See the jsFiddle for extra code to be able to use DateToString('Sun May 11,2014', 'USA');
//formatString = CountryCodeToDateFormat(formatString);
var dateObject = {
M: inDate.getMonth() + 1,
d: inDate.getDate(),
D: inDate.getDate(),
h: inDate.getHours(),
m: inDate.getMinutes(),
s: inDate.getSeconds(),
y: inDate.getFullYear(),
Y: inDate.getFullYear()
};
// Build Regex Dynamically based on the list above.
// It should end up with something like this: "/([Yy]+|M+|[Dd]+|h+|m+|s+)/g"
var dateMatchRegex = joinObj(dateObject, "+|") + "+";
var regEx = new RegExp(dateMatchRegex,"g");
formatString = formatString.replace(regEx, function(formatToken) {
var datePartValue = dateObject[formatToken.slice(-1)];
var tokenLength = formatToken.length;
// A conflict exists between specifying 'd' for no zero pad -> expand
// to '10' and specifying yy for just two year digits '01' instead
// of '2001'. One expands, the other contracts.
//
// So Constrict Years but Expand All Else
if (formatToken.indexOf('y') < 0 && formatToken.indexOf('Y') < 0)
{
// Expand single digit format token 'd' to
// multi digit value '10' when needed
var tokenLength = Math.max(formatToken.length, datePartValue.toString().length);
}
var zeroPad = (datePartValue.toString().length < formatToken.length ? "0".repeat(tokenLength) : "");
return (zeroPad + datePartValue).slice(-tokenLength);
});
return formatString;
}
使用示例:
DateToString('Sun May 11,2014', 'MM/DD/yy');
DateToString('Sun May 11,2014', 'yyyy.MM.dd');
DateToString(new Date('Sun Dec 11,2014'),'yy-M-d');
你可以:
函数formatDate(日期){
var d = new Date(日期),
月= " + (d.getMonth() + 1) ",
day = " + d.getDate(),
year = d.g getfullyear ();
如果(月。长度< 2)
月= '0' +月;
如果一天。长度< 2)
Day = '0' + Day;
返回[年,月,日].join('-');
}
console.log(formatDate('Sun May 11,2014'));
使用的例子:
console.log(formatDate('Sun May 11,2014'));
输出:
2014-05-11
JSFiddle的演示:http://jsfiddle.net/abdulrauf6182012/2Frm3/