js处理日期,javascript如何进行时间计算
1、Date.parse()的使用// 返回自定义时间戳Date.parse(“2017/03/19”)
//返回当前时间的事件戳Date.parse(new Date());
//结果为16095887727332、Date.getTime()的使用
var dateNow = new Date();var ff = dateNow.getTime();console.log(ff);//打印
创建 Date 对象Date 对象由新的 Date() 构造函数创建。
1、Date.parse()的使用// 返回自定义时间戳Date.parse(“2017/03/19”)
//返回当前时间的事件戳Date.parse(new Date());
//结果为16095887727332、Date.getTime()的使用
var dateNow = new Date();var ff = dateNow.getTime();console.log(ff);//打印出来的是1609588253222
3、巧妙写法 new Date()
var aa = new Date();console.log(aa);//返回值为:1609588248000
4、new Date().valueOf()
var aa = new Date().valueOf();console.log(aa);//返回值为:1609588243000
5、Date.now()
var aa = Date.now();console.log(aa);//返回值为:1609588231517有 4 种方法创建新的日期对象:
new Date()new Date(year, month, day, hours, minutes, seconds, milliseconds)new Date(milliseconds)new Date(date string)var d = new Date(2021, 1, 1, 10, 33, 30, 0);
new Date(milliseconds)new Date(milliseconds) 创建一个零时加毫秒的新日期对象:var d = new Date(0); // Thu Jan 01 1970 08:00:00 GMT 0800 (伊尔库茨克标准时间)
JS获取当前时间是年份或月份var myDate = new Date();myDate.getYear(); //获取当前年份(2位)myDate.getFullYear(); //获取完整的年份(4位,1970-???)myDate.getMonth(); //获取当前月份(0-11,0代表1月)myDate.getDate(); //获取当前日(1-31)myDate.getDay(); //获取当前星期X(0-6,0代表星期天)myDate.getTime(); //获取当前时间(从1970.1.1开始的毫秒数)myDate.getHours(); //获取当前小时数(0-23)myDate.getMinutes(); //获取当前分钟数(0-59)myDate.getSeconds(); //获取当前秒数(0-59)myDate.getMilliseconds(); //获取当前毫秒数(0-999)myDate.toLocaleDateString(); //获取当前日期var mytime=myDate.toLocaleTimeString(); //获取当前时间myDate.toLocaleString( ); //获取日期与时间
时间格式化 – 转换为:yyyy-MM-dd hh:mm:ss格式function timestampToTime(timestamp) {var date = new Date(timestamp * 1000);//时间戳为10位需*1000,时间戳为13位的话不需乘1000var Y = date.getFullYear() ‘-’;var M = (date.getMonth() 1
设置日期,当前日期的前七天var myDate = new Date(); //获取今天日期myDate.setDate(myDate.getDate() - 7);var dateArray = [];var dateTemp;var flag = 1;for (var i = 0; i
获取系统前一周的时间var oneweekdate = new Date(nowdate-7243600*1000);var y = oneweekdate.getFullYear();var m = oneweekdate.getMonth() 1;var d = oneweekdate.getDate();var formatwdate = y ’-’ m ’-’ d;alert(formatwdate);
获取系统前一个月的时间nowdate.setMonth(nowdate.getMonth()-1);var y = nowdate.getFullYear();var m = nowdate.getMonth() 1;var d = nowdate.getDate();var formatwdate = y ’-’ m ’-’ d;alert(formatwdate);
获取一星期前的时间var now = new Date();var date = new Date(now.getTime() - 7 * 24 * 3600 * 1000);var year = date.getFullYear();var month = date.getMonth() 1;var day = date.getDate();var hour = date.getHours();var minute = date.getMinutes();var second = date.getSeconds();alert(year ‘-’ month ‘-’ day ’ ’ hour ‘:’ minute ‘:’ second);
文章评论