js 字符串格式化为时间格式

首先介绍一下我遇到的坑,找了几个关于字符串转时间的,他们都可以就我用的时候不行。

我的原因,我的字符串是MYSQL拿出来的不是标准的时间格式,是不会转成功的。

解决思路:先将字符串转为标准时间格式的字符串,在转为时间

原文链接:https://www.jb51.net/article/66385.htm

//字符串转日期格式,strDate要转为日期格式的字符串 
function getDate(strDate) { 
  var st = strDate; 
  var a = st.split(" "); //这个根据你的字符串决定,如果中间为T则改T
  var b = a[0].split("-"); 
  var c = a[1].split(":"); 
  var date = new Date(b[0], b[1], b[2], c[0], c[1], c[2]);
  return date; 
} 

然后就是网上各种转换方式了:

原文链接:https://blog.csdn.net/yangxiaovip/article/details/40429155

function formatDate(date, format) {   
    if (!date) return;   
    if (!format) format = "yyyy-MM-dd";   
    switch(typeof date) {   
        case "string":   
            date = new Date(date.replace(/-/, "/"));   
            break;   
        case "number":   
            date = new Date(date);   
            break;   
    }    
    if (!date instanceof Date) return;   
    var dict = {   
        "yyyy": date.getFullYear(),   
        "M": date.getMonth() + 1,   
        "d": date.getDate(),   
        "H": date.getHours(),   
        "m": date.getMinutes(),   
        "s": date.getSeconds(),   
        "MM": ("" + (date.getMonth() + 101)).substr(1),   
        "dd": ("" + (date.getDate() + 100)).substr(1),   
        "HH": ("" + (date.getHours() + 100)).substr(1),   
        "mm": ("" + (date.getMinutes() + 100)).substr(1),   
        "ss": ("" + (date.getSeconds() + 100)).substr(1)   
    };       
    return format.replace(/(yyyy|MM?|dd?|HH?|ss?|mm?)/g, function() {   
        return dict[arguments[0]];   
    });                   
}  

最后说明一下 我发的只是两个方法,是原文的,并无连贯性,并未做处理。

我说的重点是问题的思路和原因。

个人笔记,转载指定链接

原文地址:https://www.cnblogs.com/hkzw/p/11459119.html