js中格式化时间字符串,时间加减

下面介绍一种在js中,关于时间格式的转换。

<script>   
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]];   
    });                   
}   
  
alert(formatDate("2010-04-30", "yyyy-MM-dd HH:mm:ss"));   
alert(formatDate("2010-4-29 1:50:00", "yyyy-MM-dd HH:mm:ss"));   
 </script>
var datestr="/Date(1408291200000+0800)/"; //模拟我们返回的json日期格式

var newdate=eval(datastr.replace(///g, '')); // 通过这个方法日期被格式化成了"Wed Aug 20 2014 18:54:10 GMT+0800 (中国标准时间)"标准时间格式

然后在调用上面的方法:

alert(formatDate(newdate, "yyyy-MM-dd HH:mm:ss"));   
alert(formatDate(newdate, "yyyy-MM-dd")); 

返回结果:  

2014-08-20 19:00:13

2014-08-20  

时间加几天
var dateTime=new Date();
// 加一天
dateTime=dateTime.setDate(dateTime.getDate()+1);
dateTime=new Date(dateTime);


 
原文地址:https://www.cnblogs.com/xiaoliu66007/p/7722381.html