js 日期格式转换(转载)

1.当前时间转为 “yyyy-MM-dd HH:MM:SS”

function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
            + " " + date.getHours() + seperator2 + date.getMinutes()
            + seperator2 + date.getSeconds();
    return currentdate;
}

2.任意日期转为 “yyyy-MM-dd HH:MM:SS”,将  date 变量作为参数传递。

3.任意日期转为 “yyyy-MM-dd ”,稍微改动即可。

       // 获取当前的日期时间 格式“yyyy-MM-dd”
        function getFormatDate(date) {
            //var date = new Date();
            var seperator1 = "-";
            var month = date.getMonth() + 1;
            var strDate = date.getDate();
            if (month >= 1 && month <= 9) {
                month = "0" + month;
            }
            if (strDate >= 0 && strDate <= 9) {
                strDate = "0" + strDate;
            }
            var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate;
                 
            return currentdate;
        }

4.任意日期转为 “ HH:MM:SS ”,稍微改动即可,省略。

5. 将指定的格式转换为"yyyy-MM-dd"的格式,代码如下:

    var oldTime = (new Date("2012/12/25 20:11:11")).getTime();
    var curTime = new Date(oldTime).format("yyyy-MM-dd");
    console.log(curTime);

6. 将 "时间戳" 转换为 "年月日" 的格式.

  比如如下代码: 

    var da = 1402233166999;
    da = new Date(da);
    var year = da.getFullYear();
    var month = da.getMonth()+1;
    var date = da.getDate();
    console.log([year,month,date].join('-'));

转载来源:https://www.cnblogs.com/tugenhua0707/p/3776808.html

原文地址:https://www.cnblogs.com/hao-1234-1234/p/8857001.html