1.判断是否为同一天
function isSameFay(t) { return new Date(t).toDateString() === new Date().toDateString(); }
2. IOS将时间字符串转换为时间戳NAN
var data = "2019-01-22 11:11:11"; //将"-"换成"/",IOS不支持‘-’ var time = data.replace(/-/g, '/'); //转换成时间戳 time = new Date(time).getTime()
3.时间戳转化为字符串
function getStringFromDate(date, withHMS) {//withHMS:是否返回时分秒 date = date == null ? new Date() : date; var seperator1 = "-"; var month = date.getMonth() + 1; var strDate = date.getDate(); if(month >= 1 && month <= 9) { month = "0" + month; } if(strDate >= 0 && strDate <= 9) { strDate = "0" + strDate; } var result = date.getFullYear() + seperator1 + month + seperator1 + strDate; if(withHMS) { var seperator2 = ":"; result += " " + (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + seperator2 + (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + seperator2 + (date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds()); } return result; }
4.字符串转化为时间
function getDateFromString(dateString) { var parts = dateString.split(' '); if(parts.length < 1) { return null; } var part1 = parts[0].split('-'); if(part1.length != 3) { return null; } var d = new Date(part1[0], part1[1] - 1, part1[2]); if(parts[1] && d) { var part2 = parts[1].split(':'); if(part2) { d.setHours(part2[0]); d.setMinutes(part2[1]); d.setSeconds(part2[2]); } } return d; }
5.比较日期大小
function compDate(date1, date2) { var a = Date.parse(date1) - Date.parse(date2); // console.log("a:"+a); if(a < 0) { // console.log("date1小!"); } else if(a > 0) { // console.log("date1大!"); } else if(a == 0) { // console.log("时间相等!"); } else { return 'exception'; } return a; }