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

旧城等待, 2022-10-01 00:59 550阅读 0赞

一、时间戳转化成日期

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

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Date对象</title>
  6. </head>
  7. <body>
  8. <script>
  9. function getLocalTime(nS) {
  10. return new Date(parseInt(nS) * 1000).Format("yyyy-MM-dd hh:mm:ss");
  11. }
  12. Date.prototype.Format = function(fmt) {//author: meizz
  13. var o = {
  14. "M+" : this.getMonth() + 1, //月份
  15. "d+" : this.getDate(), //日
  16. "h+" : this.getHours(), //小时
  17. "m+" : this.getMinutes(), //分
  18. "s+" : this.getSeconds(), //秒
  19. "q+" : Math.floor((this.getMonth() + 3) / 3), //季度
  20. "S" : this.getMilliseconds() //毫秒
  21. };
  22. if (/(y+)/.test(fmt))
  23. fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  24. for (var k in o)
  25. if (new RegExp("(" + k + ")").test(fmt))
  26. fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  27. return fmt;
  28. }
  29. console.log(getLocalTime(1490586664)); //2017-03-27 11:51:04
  30. </script>
  31. </body>
  32. </html>

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

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

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

发表评论

表情:
评论列表 (有 0 条评论,550人围观)

还没有评论,来说两句吧...

相关阅读