2018/7/26格式化成2018-07
怎么写啊
function leftpad (str, len, ch) {
// str:要转换的字符串/数字、len:转多长、ch:拼接符
str = String(str)
var i = -1
if (!ch && ch !== 0) ch = ' '
len = len - str.length
while (++i < len) {
str = ch + str
}
return str
}
function revertDate(date){
var str = date.split('/');
var res = str[0] + '-' + leftpad(str[1], 2, '0');
return res;
}
console.log(revertDate('2018/7/26'));
泻药,只是面对这个题目的话:('2018/7/26').replace(/\b(\d)\b/g, '0$1').replace(/^(\d{4})\/(\d{2})\/\d{2}/,'$1-$2')
分两步操作:
/
为 -
其中,$1 $2 是分组操作,代表正则中()中的匹配内容,$1就是第一个括号中的$2就是第二个括号中的,如果存在嵌套,那么从外向里数。
2018-06-20 16:40 转换
Date.prototype.Format = function(fmt) {
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt))
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
};
//使用
var testTimeB = '2018-06-20 16:40';
testTimeB = testTimeB.replace(/-/g, "/"); // ios 兼容时间 将-替换为/
var timeB = new Date(testTimeB).Format('yyyy/MM/dd hh:mm');
10 回答11.1k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.7k 阅读✓ 已解决
3 回答2.3k 阅读✓ 已解决
3 回答2.1k 阅读✓ 已解决