您的位置:首页 > Web前端 > JavaScript

js中日期和天数 计算新日期

2013-02-27 13:53 501 查看
方法一:

var strDate = "2013-04-05";
if(strDate.match(/^(\d{4})\-(\d{2})\-(\d{2})$/) == null) {//正则表达式 判断strDate是否为yyyy-MM-dd格式
return false;
}
var DayUnit = ds_ddmx.field("DayUnit").value;//年、月、日//小气单位
var InEffectDay = ds_ddmx.field("InEffectDay").value;//数字。几年,几月、几日//为有效期

var valdate = new Date(strDate.replace(/-/,"/"));//把“yyyy-MM-dd”格式转换为date类型。
if (fld == "producedate") {
if(DayUnit == 2) {
valdate.setYear(valdate.getYear() + InEffectDay);//日期加年的操作。
} else if (DayUnit == 0){
valdate.setMonth(valdate.getMonth() + InEffectDay);//日期加月的操作。
} else if (DayUnit == 1) {
valdate.setDate(valdate.getDate() + InEffectDay);//日期加天数的操作。
}
ds_ddmx.field("valdate").value = valdate.toText("yyyy-MM-dd");//date类型转换为String类型。toText的方法来自于下面定义的正则表达式。
}

方法二:

//调用返回日期函数 用参数第一个日期加第二个参数 获得新的日期 结果为  2013-02-26

addDate(‘2013-02-27’, -1);

//函数返回新日期

function addDate(oldDate,addDays){
var newDate  =new Date(oldDate.replace(/[^\d]/g,"/").replace(/\\$/g,""));
newDate.setDate(newDate.getDate()+addDays);
for (m = 0;m<ds_ddmx.recordCount;m++) {
ds_ddmx.setValueAt(m,"ArrDate",newDate.toText("yyyy-MM-dd"));//把新日期赋值
}

}

//正则表达式

Date.prototype.toText = function(style){

    if (style == null) style = 'yyyy-MM-dd hh:mm';

    var compare = {

         'y+' : 'y', 

         'M+' : 'M',  //格式 月份:01到12

         'o+' : 'o',  //格式 月份:1 到12

         'd+' : 'd',  //格式 天 : 01到31

         'D+' : 'D',  //格式 天 : 1 到31

         'h+' : 'h',  //格式 小时:00到23

         'H+' : 'H',  //格式 小时:0 到23

         'm+' : 'm',  //格式 分钟:00到59

         'i+' : 'i',  //格式 分钟:0 到59

         's+' : 's',  //格式 秒 : 00到59

         'S+' : 'S'   //格式 秒 : 0到59

    };

    var result = {

         'y':this.getFullYear(),

         'M':(this.getMonth() < 9) ? ("0" + (1+this.getMonth())) : (1+this.getMonth()),

         'o':(1+this.getMonth()),

         'd':(this.getDate() < 10) ? ("0" + this.getDate()) : this.getDate(),

         'D':this.getDate(),

         'h':(this.getHours()< 10) ? ("0" + this.getHours()):this.getHours(),

         'H':this.getHours(),

         'm':(this.getMinutes()<10)? ("0" + this.getMinutes()):this.getMinutes(),

         'i':this.getMinutes(),

         's':(this.getSeconds()<10)? ("0" + this.getSeconds()):this.getSeconds(),

         'S':this.getSeconds()

    };

    var tmp = style;

    for( var k in compare){

        if (new RegExp('(' + k + ')').test(style)) {

            tmp = tmp.replace(RegExp.$1,result[compare[k]]);

       };

   };

   return tmp;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: