首页 > 日期相减如何兼容IE?

日期相减如何兼容IE?

var oDate=new Date();//今天
var oYear=oDate.getFullYear();//取得今年年份
var oMonth=oDate.getMonth();//取得今月月份
var fDate=new Date(oYear+','+(oMonth+1)+','+1);//取得本月第一天
var nMonth=new Date(oYear+','+(oMonth+2)+','+1);//取得下个月第一案
var lMonth=new Date(oYear+','+(oMonth)+','+1);//取得上个月第一天
var firstPos=fDate.getDay()-1;//1号在日历中的位置
var MonthDay=(nMonth-fDate)/1000/60/60/24;//这个月有几天 -->这里IE浏览器的结果是NAN
var lastMonthDay=(fDate-lMonth)/1000/60/60/24;//上个月有几天 -->这里IE浏览器的结果是NAN

日期做减法如何兼容IE?
网上找了半天也没有一个满意的答案,求大神赐教。


new Date(oYear+','+(oMonth+1)+','+1); 不需要转换成字符串

new Date(年, 月, 日, 时, 分, 秒, 毫秒)

var oDate=new Date();//今天
var oYear=oDate.getFullYear();//取得今年年份
var oMonth=oDate.getMonth();//取得今月月份

//取得本月第一天
var fDate=new Date(oYear+','+(oMonth+1)+','+1);//IE中为 NaN
var fDate=new Date(oYear, (oMonth+1), 1);

//取得下个月第一案
var nMonth=new Date(oYear+','+(oMonth+2)+','+1);//IE中为 NaN
var nMonth=new Date(oYear, (oMonth+2), 1);

//取得上个月第一天
var lMonth=new Date(oYear+','+(oMonth)+','+1);//IE中为 NaN
var lMonth=new Date(oYear, (oMonth), 1);

//1号在日历中的位置
var firstPos=fDate.getDay()-1;

var MonthDay=(nMonth-fDate)/1000/60/60/24;//这个月有几天 -->IE中正常
var lastMonthDay=(fDate-lMonth)/1000/60/60/24;//上个月有几天 -->IE中正常

我想你要的答案在《JavaScript高级程序设计 第三版》第99页第二段。使用new Date("这里是字符串")这种方式可能会出错,推荐直接使用new Date(年,月,日)//这里的年月日都是数字。


换moment.js 来计算。


你在做万年历吗?

【热门文章】
【热门文章】