日期:2014-05-16  浏览次数:20477 次

JavaScript如何获得某一天的前一天日期
网上看到一段代码,可以获得系统当前日期的前一天。
如何获得任意选定一天的前一天呢?
不要说直接减1啊。例如:20120301减1就为20120300了,应该是20120229
系统当前日期的前一天代码:
JScript code
    function GetDay()   
    {   
        var today=new Date();
        var yesterday_milliseconds=today.getTime()-1000*60*60*24;
        
        var yesterday=new Date();      
        yesterday.setTime(yesterday_milliseconds);      
           
        var strYear=yesterday.getFullYear();   
        var strDay=yesterday.getDate();   
        var strMonth=yesterday.getMonth()+1;   
        if(strMonth<10)   
        {   
            strMonth="0"+strMonth;   
        }   
        var strYesterday=strYear+"-"+strMonth+"-"+strDay;   
        alert(strYesterday);
    }

如何获得任意一天的前一天呢?

------解决方案--------------------
var d = new Date(2012, 0, 1);
d.setTime(d.getTime()-24*60*60*1000);

------解决方案--------------------
new Date(d.getFullYear(),d.getMonth(),d.getDate()-1)
------解决方案--------------------
探讨

------解决方案--------------------
JScript code


s = "20120301";
alert(getPreDay(s));

function getPreDay(s){
    var y = parseInt(s.substr(0,4), 10);
    var m = parseInt(s.substr(4,2), 10)-1;
    var d = parseInt(s.substr(6,2), 10);
    var dt = new Date(y, m, d-1);
    y = dt.getFullYear();
    m = dt.getMonth()+1;
    d = dt.getDate();
    m = m<10?m:"0"+m;
    d = d<10?d:"0"+d;
    return y + "" + m + "" + d;
}

------解决方案--------------------
正解
探讨

new Date(d.getFullYear(),d.getMonth(),d.getDate()-1)

------解决方案--------------------
探讨

JScript code


s = "20120301";
alert(getPreDay(s));

function getPreDay(s){
var y = parseInt(s.substr(0,4), 10);
var m = parseInt(s.substr(4,2), 10)-1;
var d = parseInt(s.substr(6,2), 10……

------解决方案--------------------
探讨
JScript code


s = "20120301";
alert(getPreDay(s));

function getPreDay(s){
var y = parseInt(s.substr(0,4), 10);
var m = parseInt(s.substr(4,2), 10)-1;
var d = parseInt(s.substr(6……

------解决方案--------------------
用你这个简单改一下就可以
JScript code

function GetDay(year, month, day)   
    {   
        var today=new Date(year, month-1 ,day);
        var yesterday_milliseconds=today.getTime()-1000*60*60*24;
        
        var yesterday=new Date();      
        yesterday.setTime(yesterday_milliseconds);      
           
        var strYear=yesterday.getFullYear();   
        var strDay=yesterday.getDate();   
        var strMonth=yesterday.getMonth()+1;   
        if(strMonth<10)   
        {   
            strMonth="0"+strMonth;   
        }   
        var strYesterday=strYear+"-"+strMonth+"-"+strDay;   
        alert(strYesterday);
    }
    GetDay(2012, 1, 5);