首页 > 代码库 > js获取当前日期、前一天、后一天的日期的例子
js获取当前日期、前一天、后一天的日期的例子
<script> function addByTransDate(dateParameter, num) { var translateDate = "", dateString = "", monthString = "", dayString = ""; translateDate = dateParameter.replace("-", "/").replace("-", "/"); var newDate = new Date(translateDate); newDate = newDate.valueOf(); newDate = newDate + num * 24 * 60 * 60 * 1000; newDate = new Date(newDate); //如果月份长度少于2,则前加 0 补位 if ((newDate.getMonth() + 1).toString().length == 1) { monthString = 0 + "" + (newDate.getMonth() + 1).toString(); } else { monthString = (newDate.getMonth() + 1).toString(); } //如果天数长度少于2,则前加 0 补位 if (newDate.getDate().toString().length == 1) { dayString = 0 + "" + newDate.getDate().toString(); } else { dayString = newDate.getDate().toString(); } dateString = newDate.getFullYear() + "-" + monthString + "-" + dayString; return dateString; } function reduceByTransDate(dateParameter, num) { var translateDate = "", dateString = "", monthString = "", dayString = ""; translateDate = dateParameter.replace("-", "/").replace("-", "/"); var newDate = new Date(translateDate); newDate = newDate.valueOf(); newDate = newDate - num * 24 * 60 * 60 * 1000; newDate = new Date(newDate); //如果月份长度少于2,则前加 0 补位 if ((newDate.getMonth() + 1).toString().length == 1) { monthString = 0 + "" + (newDate.getMonth() + 1).toString(); } else { monthString = (newDate.getMonth() + 1).toString(); } //如果天数长度少于2,则前加 0 补位 if (newDate.getDate().toString().length == 1) { dayString = 0 + "" + newDate.getDate().toString(); } else { dayString = newDate.getDate().toString(); } dateString = newDate.getFullYear() + "-" + monthString + "-" + dayString; return dateString; } //得到日期 主方法 function showTime(pdVal) { var trans_day = ""; var cur_date = new Date(); var cur_year = new Date().format("yyyy"); var cur_month = cur_date.getMonth() + 1; var real_date = cur_date.getDate(); cur_month = cur_month > 9 ? cur_month : ("0" + cur_month); real_date = real_date > 9 ? real_date : ("0" + real_date); eT = cur_year + "-" + cur_month + "-" + real_date; if (pdVal == 1) { trans_day = addByTransDate(eT, 1); } else if (pdVal == -1) { trans_day = reduceByTransDate(eT, 1); } else { trans_day = eT; } //处理 return trans_day; }
调用示例:
//当前日期
var tcur=showTime(0);
//前一天
var tqyt=showTime(-1);
//后一天
var thyt=showTime(1);
附,JS得到当前日期时间的小例子
function currentTime() { var d = new Date(); var vYear = d.getFullYear(); var vMon = d.getMonth() + 1; var vDay = d.getDate(); var h = d.getHours(); www.jquerycn.cn var m = d.getMinutes(); var se = d.getSeconds(); var s = vYear+"-"+ (vMon < 10 ? "0" + vMon : vMon)+"-" + (vDay < 10 ? "0" + vDay : vDay)+" " + (h < 10 ? "0" + h : h)+":" + (m < 10 ? "0" + m : m)+":" + (se < 10 ? "0" + se : se); return s; }
js获取当前日期、前一天、后一天的日期的例子
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。