时间戳与标准时间的转换

获取时间戳的方法

1.Date.now() 方法返回自1970年1月1日 00:00:00 UTC到当前时间的毫秒数(获取当前时间)

2.getTime 方法的返回值一个数值,表示从1970年1月1日0时0分0秒距离该日期对象所代表时间的毫秒数

3.Date.parse() 方法解析一个表示某个日期的字符串,并返回从1970-1-1 00:00:00 UTC 到该日期对象(该日期对象的UTC时间)的毫秒数


4.valueOf() 该方法返回以数值格式表示的一个 Date 对象的原始值,从1970年1月1日0时0分0秒(UTC,即协调世界时)到该日期对象所代表时间的毫秒数。(与getTime没有区别)


date.parse 与 getTime 的区别

Date.parse() :时间字符串可以直接Date.parse(datestring),不需要 new Date()
Date.getTime() :需要将时间字符串先new Date(),再使用Date.getTime()

时间戳转化为日期字符串

方法一:

var now = new Date();
var yy = now.getFullYear();      //年
var mm = now.getMonth() + 1;     //月
var dd = now.getDate();          //日
var hh = now.getHours();         //时
var ii = now.getMinutes();       //分
var ss = now.getSeconds();       //秒
var clock = yy + "-";
if(mm < 10) clock += "0";
clock += mm + "-";
if(dd < 10) clock += "0";
clock += dd + " ";
if(hh < 10) clock += "0";
clock += hh + ":";
if (ii < 10) clock += '0'; 
clock += ii + ":";
if (ss < 10) clock += '0'; 
clock += ss;
document.write(clock);     //获取当前日期

方法二

//时间戳转时间
    date_format(val) {
      var date = '';
      var hours = parseInt(val / 1000 / 60 / 60 % 24, 10); //计算剩余的小时
      var minutes = parseInt(val / 1000 / 60 % 60, 10); //计算剩余的分钟
      var seconds = parseInt(val / 1000 % 60, 10); //计算剩余的秒数
      if (hours < 10) {
        hours = '0' + hours;
      };
      if (minutes < 10) {
        minutes = '0' + minutes;
      };
      if (seconds < 10) {
        seconds = '0' + seconds;
      };
      date = hours + ':' + minutes + ':' + seconds;
      return date;
    }

方法三 (使用API dayjs)
Day.js安装

npm install dayjs --save

使用

var dayjs = require('dayjs');
dayjs().format();

github地址 :https://github.com/iamkun/dayjs
dayJs中文文档 :https://github.com/iamkun/dayjs/blob/master/docs/zh-cn/API-reference.md

你可能感兴趣的:(时间戳与标准时间的转换)