js中使用eval()方法将字符串转换成日期格式、并获取指定时间的日期
1、在js中eval()方法将字符串格式数据转换成日期格式
function getDate(strDate) { //strDate为需要转换成日期格式的字符串 var date = eval('new Date(' + strDate.replace(/\d+(?=-[^-]+$)/, function (a) { return parseInt(a, 10) - 1; }).match(/\d+/g) + ')'); return date; }
2、获取当前日期的前一天日期
function getYestoday(date){ var yesterday_milliseconds=date.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; } datastr = strYear+"-"+strMonth+"-"+strDay; return datastr; }
3、获得上个月在昨天这一天的日期
function getLastMonthYestday(date){ var daysInMonth = new Array([0],[31],[28],[31],[30],[31],[30],[31],[31],[30],[31],[30],[31]); var strYear = date.getFullYear(); var strDay = date.getDate(); var strMonth = date.getMonth()+1; if(strYear%4 == 0 && strYear%100 != 0){ daysInMonth[2] = 29; } if(strMonth - 1 == 0) { strYear -= 1; strMonth = 12; } else { strMonth -= 1; } strDay = daysInMonth[strMonth] >= strDay ? strDay : daysInMonth[strMonth]; if(strMonth<10) { strMonth="0"+strMonth; } if(strDay<10) { strDay="0"+strDay; } datastr = strYear+"-"+strMonth+"-"+strDay; return datastr; }
4、获得上一年在昨天这一天的日期
function getLastYearYestdy(date){ var strYear = date.getFullYear() - 1; var strDay = date.getDate(); var strMonth = date.getMonth()+1; if(strMonth<10) { strMonth="0"+strMonth; } if(strDay<10) { strDay="0"+strDay; } datastr = strYear+"-"+strMonth+"-"+strDay; return datastr; }
5、获得下个月在昨天这一天的日期
function getLastMonthYestdy2(date){ var daysInMonth = new Array([0],[31],[28],[31],[30],[31],[30],[31],[31],[30],[31],[30],[31]); var strYear = date.getFullYear(); var strDay = date.getDate(); var strMonth = date.getMonth()+1; if(strYear%4 == 0 && strYear%100 != 0){ daysInMonth[2] = 29; } if(strMonth + 1 == 13) { strYear += 1; strMonth = 1; } else { strMonth += 1; } strDay = daysInMonth[strMonth] >= strDay ? strDay : daysInMonth[strMonth]; if(strMonth<10) { strMonth="0"+strMonth; } if(strDay<10) { strDay="0"+strDay; } datastr = strYear+"-"+strMonth+"-"+strDay; return datastr; }
6、测试
$(function() { var strDate = '2014-06-11'; $("#test").html("用eval()方法将字符串转换为时间格式:" + getDate(strDate) + "<br/>" + "获取当前日期的前一天日期:" + getYestoday(getDate(strDate)) + "<br/>" + "获得上个月在昨天这一天的日期:" + getLastMonthYestday(getDate(strDate)) + "<br/>" + "获得上一年在昨天这一天的日期:" + getLastYearYestdy(getDate(strDate)) + "<br/>" + "获得下个月在昨天这一天的日期:" + getLastMonthYestdy2(getDate(strDate)) + "<br/>"); })
7、测试结果
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。