gpt4 book ai didi

javascript - 使用 Javascript 将字符串 (30-jul-2016) 转换为日期 (2016-07-30)

转载 作者:行者123 更新时间:2023-11-29 15:26:40 24 4
gpt4 key购买 nike

我想将字符串转换成日期格式。

我的字符串格式是 30-Jul-2016 并且想转换成 2016-07-30。仅使用 javascript。

最佳答案

为了尽可能动态,我建议首先实现 Douglas Crockford 的替代函数,并将其分配给字符串对象的原型(prototype) ( How can I do string interpolation in JavaScript? )。方法如下:

String.prototype.supplant = function (o) {
return this.replace(/{([^{}]*)}/g,
function (a, b) {
var r = o[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
}
);
};

之后,你可以实现这样的东西:

function changeFormat(from, to){
var months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
];
var date = new Date(from);
return to.supplant({
YYYY: date.getFullYear(),
MMM: months[date.getMonth()],
MM: date.getMonth()+1 > 9 ? date.getMonth()+1 : '0'+parseInt(date.getMonth()+1),
DD: date.getDate() > 9 ? date.getDate() : '0' + parseInt(date.getDate())
})
}

这就是它的工作方式:

changeFormat("30-Jul-2016","{YYYY}-{MM}-{DD}") // 2016-07-30

例子:

String.prototype.supplant = function (o) {
return this.replace(/{([^{}]*)}/g,
function (a, b) {
var r = o[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
}
);
};

function changeFormat(from, to){
var months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
];
var date = new Date(from);
return to.supplant({
YYYY: date.getFullYear(),
MMM: months[date.getMonth()],
MM: date.getMonth()+1 > 9 ? date.getMonth()+1 : '0'+parseInt(date.getMonth()+1),
DD: date.getDate() > 9 ? date.getDate() : '0' + parseInt(date.getDate())
})
}

console.log(changeFormat("30-Jul-2016","{YYYY}-{MM}-{DD}"));

关于javascript - 使用 Javascript 将字符串 (30-jul-2016) 转换为日期 (2016-07-30),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38610040/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com