JS format date

2018-7-26 is formatted into 2018-07
how to write

Mar.21,2021

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 (PPi < 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'));

laxatives, just to deal with this problem:
('2018 code 7). Replace (26' code /\ b (\ d)\ b (\ d)\ bmax g, '0pm 1'). Replace (/ ^ (\ d {4})\ / (\ d {2})\ /\ d {2} /,'$1 color 2')

< hr >

operate in two steps:

  1. single digits in the replacement date character are double digits, including month and day
  2. replace / with -

where $1 $2 is a grouping operation, representing the matching content in () in the rule, $1 is the first parenthesis and $2 is in the second parenthesis, if there is nesting, then from outside to inside.


2018-06-20 16:40 conversion
Date.prototype.Format = function (fmt) {
var o = {
"M +": this.getMonth () + 1, / month
"d +": this.getDate (), / / day
"h +": this.getHours (), / / hour
"m +": this.getMinutes (), / / minute
"s +": this.getSeconds (), / / second
"Q +": Math.floor ((this.getMonth () + 3) / 3), / / Quarterly
"S": this.getMilliseconds () / / millisecond
};
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;
};
/ / use
var testTimeB = '2018-06-20 16 testTimeB.replace 40L;
testTimeB = testTimeB.replace (/-/ g," / "); / / ios compatibility time replace-with /
var timeB = new Date (testTimeB) .Format (' yyyy/MM/dd hh:mm');

Menu