HTML时间戳和日期之间的相互转化

来源:互联网 发布:类似于快刀的软件 编辑:程序博客网 时间:2024/05/22 14:02
一、时间戳转化成日期

这个很简单,只要在new Date()里传时间戳过去就可以了,然后还可以得到相应的日期,例:

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Date对象</title></head><body><script> function getLocalTime(nS) {return new Date(parseInt(nS) * 1000).Format("yyyy-MM-dd hh:mm:ss");}Date.prototype.Format = function(fmt) {//author: meizzvar o = {"M+" : this.getMonth() + 1, //月份"d+" : this.getDate(), //日"h+" : this.getHours(), //小时"m+" : this.getMinutes(), //分"s+" : this.getSeconds(), //秒"q+" : Math.floor((this.getMonth() + 3) / 3), //季度"S" : this.getMilliseconds() //毫秒};if (/(y+)/.test(fmt))fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));for (var k in o)if (new RegExp("(" + k + ")").test(fmt))fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));return fmt;}    console.log(getLocalTime(1490586664));  //2017-03-27 11:51:04</script></body></html>

二、将日期转化成时间戳
有三种方式: getTime()、valueOf()、Date.parse(要转化的日期);前两种方式可以精确到毫秒,而最后一种方式只能精确到秒毫秒用0来代替,例:

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Date对象</title></head><body><script>   var date = new Date('2014-04-23 18:55:49:123');//可以传时间,也可以不传,不传的话就是默认的当前时间  time1 = date.getTime();   time2 = date.valueOf();      time3 = Date.parse(date);  console.log(time1);  //1398250549123  console.log(time2);  //1398250549123  console.log(time3);  //1398250549000</script></body></html>


转载请注明出处:http://blog.csdn.net/chen_gp_x

0 0
原创粉丝点击