JavaScript's question about date format conversion

clipboard.png

how to convert such a date string into 2018-10-10 07:00?

Feb.09,2022

this is actually the ISO date format. The conversion code is as follows:

function formatDate(date) {  
    var y = date.getFullYear();  
    var m = date.getMonth() + 1;  
    m = m < 10 ? ('0' + m) : m;  
    var d = date.getDate();  
    d = d < 10 ? ('0' + d) : d;  
    var h = date.getHours();  
    var minute = date.getMinutes();  
    minute = minute < 10 ? ('0' + minute) : minute; 
    var second= date.getSeconds();  
    second = minute < 10 ? (second) : second;  
    return y + '-' + m + '-' + d+' '+h+':'+minute+':'+ second;  
};
var date = new Date('2018-10-10T07:36:10.902Z');
formatDate(date)

or use more

/**
 * Date String<br>
 * (M)(d)12(h)24(H)(m)(s)(E)(q) 1-2 <br>
 * (y) 1-4 (S) 1 ( 1-3 )
 *
 * @param {string} date
 * @param {string} fmt
 * @returns {string}
 * @example
 *
 * formatDate(Date.now(), 'yyyy-MM-dd hh:mm:ss.S');
 * // => 2006-07-02 08:09:04.423
 *
 * formatDate(Date.now(), 'yyyy-MM-dd E HH:mm:ss');
 * // => 2009-03-10  20:09:04
 *
 * formatDate(Date.now(), 'yyyy-MM-dd EE hh:mm:ss');
 * // => 2009-03-10  08:09:04
 *
 * formatDate(Date.now(), 'yyyy-MM-dd EEE hh:mm:ss');
 * // => 2009-03-10  08:09:04
 *
 * formatDate(Date.now(), 'yyyy-M-d h:m:s.S')
 * // => 2006-7-2 8:9:4.18
 */
/* istanbul ignore next */
function formatDate(date = new Date(), fmt = 'yyyy-MM-dd HH:mm:ss') {
  date = (typeof date === 'number' || typeof date === 'string') ? new Date(date) : date;

  var o = {
    'M+': date.getMonth() + 1, // 
    'd+': date.getDate(), // 
    'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 
    'H+': date.getHours(), // 
    'm+': date.getMinutes(), // 
    's+': date.getSeconds(), // 
    'q+': Math.floor((date.getMonth() + 3) / 3), // 
    'S': date.getMilliseconds() // 
  };
  var week = {
    '0': '\u65e5',
    '1': '\u4e00',
    '2': '\u4e8c',
    '3': '\u4e09',
    '4': '\u56db',
    '5': '\u4e94',
    '6': '\u516d'
  };

  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  }

  if (/(E+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? '\u661f\u671f' : '\u5468') : '') + week[date.getDay() + '']);
  }

  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;
}
Menu