获取日期相应时间与时间格式的方法
1.获取的时间转换为想要的日期时间格式:
function getTimetrans(){ const date = new Date();//如果date为13位不需要乘1000 const Y = date.getFullYear() + '-'; const M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-'; const D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' '; const h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'; const m = (date.getMinutes() <10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'; const s = (date.getSeconds() <10 ? '0' + date.getSeconds() : date.getSeconds()); return Y+M+D+h+m+s; }
2.获取的时间转换为星期格式:
function getWeekDate(){ const date = new Date();//如果date为13位不需要乘1000 const day = date.getDay(); const weeks = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]; const week = weeks[day]; return week; }
3.时间转换为毫秒:
1)方法一: getTime()/Date.parse()
const oldTime = (new Date("2020/08/14 15:00:00")).getTime(); //得到毫秒数 //注:日期格式是:yyyy-mm-dd hh:mm:ss需要转化格式 let startDate ='2020-08-14 15:00:00'; startDate= startDate.replace(new RegExp("-","gm"),"/"); let startDateM = (new Date(startDate)).getTime(); //得到毫秒数 //或者 let str = '2020-08-14 15:00:00'; let arr = str.split(/[- : \/]/); let startDate = Date.parse(new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5])); console.log(startDate)//1597388400000
2)方法=:valueOf()
let dateTime = '2020-08-14 15:00:00';
console.log(dateTime.valueOf());//2020-08-14 15:00:00
let dateTime1 = new Date();
console.log(dateTime1.valueOf());//1597389982770
let dateTime2 = new Date('2020-08-14 15:00:00');
console.log(dateTime2.valueOf());//1597388400000
let timeVale = Date.parse('2020-08-14 15:00:00');//APP中直接使用此方法会报错
console.log(timeVale);//1597388400000
import moment from 'moment';//react-native项目安装的插件
let timeVale2 = moment('2020-08-14 15:00:00').valueOf();//转换为毫秒(APP中使用不会报错) console.log(timeVale2);//1597388400000
4.获取当前日期前后时间:
1)获取当前日期:
getBeforeMonth(){ const date = new Date();//如果date为13位不需要乘1000 const Y = date.getFullYear() + '-'; const M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-'; const D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()); return Y+M+D; }
2)获取前几个月时间:
getFirstFewMonths(time,num){ return new Date(time).setMonth((new Date(time).getMonth() - num)); }
3)获取后几个月时间:
getNextFewMonthss(time,num){ return new Date(time).setMonth((new Date(time).getMonth() + num)); }
4)获取前几天时间:
getSomeDaysAgo(time,num){ return new Date(time).setDate((new Date(time).getDate() - num)); }
5)获取后几天时间:
getFewDaysLater(time,num){ return new Date(time).setDate((new Date(time).getDate() + num)); }
6)计算两个日期之间的天数:
/** * @param dateString1 开始日期 yyyy-MM-dd * @param dateString2 结束日期 yyyy-MM-dd * @returns {number} 如果日期相同 返回一天 开始日期大于结束日期,返回0 */ getDaysBetween(dateString1,dateString2){ var startDate = Date.parse(dateString1); var endDate = Date.parse(dateString2); if (startDate>endDate){ return 0; } if (startDate==endDate){ return 1; } var days=(endDate - startDate)/(1*24*60*60*1000); return days; }