JS格式化日期

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

阅读 2.5k
4 个回答
var a = '2018/7/26'.split('/');
var b = a[0] + '-' + (a[1] < 10 ? '0':'') + a[1];
console.log(b);
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 是分组操作,代表正则中()中的匹配内容,$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');

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题