时间常用api
创建 Date 对象 - 年 - 月 - 日 - 小时 - 分 - 秒 - 星期
var now=new Date()
var year = now.getFullYear();
var month = now.getMonth(); (月 :0 - 11 ,处理: month = month + 1;)
var date = now.getDate(); // 获取当前时间对应 月 的天数
var hour = now.getHours();
var minu = now.getMinutes();
var sec = now.getSeconds();
var day = now.getDay(); (星期:0 - 6 ,处理:var arr_week = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六");
week = arr_week[day];
)
tips:
月份是从0开始算的,省略日,则默认是按1日来算的。因此 new Date(2019, 0) 就是 2019/1/1
获取上个月
function getLastMonth(date) { var [year, month, day] = date.split('-') var lastMonthYear = year; var lastMonth = month - 1; if (lastMonth == 0) { lastMonthYear = lastMonthYear - 1; lastMonth = 12; } lastMonthLastDay = (new Date(lastMonthYear, lastMonth, 0)).getDate(); lastMonth = lastMonth - 0 >= 10 ? lastMonth : '0' + lastMonth lastMonthLastDay = lastMonthLastDay - 0 >= 10 ? lastMonthLastDay : '0' + lastMonthLastDay return { lastMonth: lastMonthYear + '-' + lastMonth, lastMonthStart: lastMonthYear + '-' + lastMonth + '-01', lastMonthEnd: lastMonthYear + '-' + lastMonth + '-' + lastMonthLastDay } }
格式化日期
export function parseTime(time, cFormat) { if (arguments.length === 0) { return '' } const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}' let date; if(!time){ return } if (typeof time === 'object') { date = time } else { let fotmatTime = formatTimeAll(time); if(/^\d+$/.test(fotmatTime)){ if(/\d{13}/.test(fotmatTime)){ date = new Date(fotmatTime); }else{ date = new Date(fotmatTime*1000); } }else{ date = new Date(fotmatTime.replace(/-/ig,'/')); } if(/\dt\d/ig.test(time)){ let add8Hour = date.getTime() + 8*3600*1000; // 后台传送 2019-09-18T09:34:18.000+0800 时间格式 ,普遍晚 8 小时 date = new Date(add8Hour); } } const formatObj = { y: date.getFullYear(), m: date.getMonth() + 1, d: date.getDate(), h: date.getHours(), i: date.getMinutes(), s: date.getSeconds(), a: date.getDay() } const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => { let value = formatObj[key] if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1] if (result.length > 0 && value < 10) { value = '0' + value } return value || 0 }) return time_str }
2.1 可根据本地时间把 Date 对象转换为字符串
new Date().toLocaleString() // "2018/8/29 下午7:45:50"
2.2 返回距 1970 年 1 月 1 日之间的毫秒数
new Date().getTime() // 1535543394634
2.3 JS中获得指定日期前或后几天对应的日期
var d = new Date();
d.setDate(d.getDate() - 2);
d.toLocaleDateString() // "2018/11/17"
var c = new Date(2017,0,1); // mouth 0 - 11
c.setDate(c.getDate() - 2);
c.toLocaleDateString() // "2016/12/30"