JS格式化日期

2018/7/26格式化成2018-07
怎么写啊

白板的微信
浏览 224回答 3
3回答

aluckdog

function leftpad &nbsp;(str, len, ch) {&nbsp; // str:要转换的字符串/数字、len:转多长、ch:拼接符&nbsp; str = String(str)&nbsp; var i = -1&nbsp; if (!ch && ch !== 0) ch = ' '&nbsp; len = len - str.length&nbsp; while (++i < len) {&nbsp; &nbsp; str = ch + str&nbsp; }&nbsp; return str}function revertDate(date){&nbsp; &nbsp; var str = date.split('/');&nbsp; &nbsp; var res = str[0] + '-' + leftpad(str[1], 2, '0');&nbsp; &nbsp; 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')分两步操作:替换日期字符中的单个位数为双位数,包括月份和天替换&nbsp;/&nbsp;为&nbsp;-其中,$1 $2 是分组操作,代表正则中()中的匹配内容,$1就是第一个括号中的$2就是第二个括号中的,如果存在嵌套,那么从外向里数。

暮色呼如

var a = '2018/7/26'.split('/');var b = a[0] + '-' + (a[1] < 10 ? '0':'') + a[1];console.log(b);
打开App,查看更多内容
随时随地看视频慕课网APP