美文网首页
获取当前时间及时间戳

获取当前时间及时间戳

作者: 那小白 | 来源:发表于2018-12-24 15:15 被阅读0次

1.获取系统当前时间

var myDate = new Date();//获取系统当前时间

2.获取特定格式的时间

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( ); //获取日期与时间

3.获取当前时间戳

(1)var timestamp =Date.parse(new Date());

from W3C的javascript

注:得到的结果:1280977330000 注意:这里得到的结果将后三位(毫秒)转换成了000显示,使用时可能会出现问题。例如动态添加页面元素id的时候,不建议使用。

(2)vartimestamp =(newDate()).valueOf();

结果:1280977330748

(3)vartimestamp=newDate().getTime();

结果:1280977330748

注:

     js中单独调用new Date(),例如document.write(new Date());显示的结果是:Mar 31 10:10:43 UTC+0800 2012 这种格式的时间

     但是用new Date() 参与计算会自动转换为从1970.1.1开始的毫秒数。

总结: js 获取当前年月日时分秒星期

$("#aa").click(function () {

var date = new Date();

this.year = date.getFullYear();

this.month = date.getMonth() + 1;

this.date = date.getDate();

this.day = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六")[date.getDay()];

this.hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();

this.minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();

this.second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();

var currentTime = "现在是:" + this.year + "年" + this.month + "月" + this.date + "日 " + this.hour + ":" + this.minute + ":" + this.second + " " + this.day;

alert(currentTime);

});

W3C的Date具体讲解:    http://www.w3school.com.cn/jsref/jsref_obj_date.asp

相关文章

网友评论

      本文标题:获取当前时间及时间戳

      本文链接:https://www.haomeiwen.com/subject/ghpjkqtx.html