javascript to time format

WBOY
Release: 2023-05-16 14:02:07
Original
2212 people have browsed it

在开发中,时间格式的转换是比较常见的操作。其中,JavaScript提供了多种方法来转换时间格式,本文将介绍几种常见的转换方式。

一、时间戳转日期

时间戳是指自1970年1月1日00:00:00以来的秒数,JavaScript提供了将时间戳转成日期的方法。代码如下:

var timestamp = 1617223881; // 时间戳

var date = new Date(timestamp * 1000); // 时间戳转日期,注意要乘以1000

console.log(date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds());
Copy after login

以上代码中,先定义了一个时间戳变量,然后使用new Date()方法将时间戳转成日期对象。注意,由于JavaScript中的时间戳是以毫秒计算的,而Unix时间戳是以秒计算的,因此需要将时间戳乘以1000。

二、日期转时间戳

如果需要将日期转成时间戳,JavaScript也提供了相应的方法。代码如下:

var date = new Date('2021-04-01 12:34:56');

var timestamp = date.getTime() / 1000;

console.log(timestamp);
Copy after login

以上代码中,先定义了一个日期对象,然后使用getTime()方法获取该日期对象的毫秒数,最后将毫秒数除以1000得到时间戳。需要注意的是,getTime()方法返回的是毫秒数,因此在转换成时间戳时需要除以1000。

三、日期格式化

如果需要将日期格式化成指定的格式,JavaScript也提供了相应的方法。例如,需要将日期格式化成yyyy-MM-dd HH:mm:ss的格式,代码如下:

var date = new Date('2021-04-01 12:34:56');

function format(date, fmt) {
  var o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'H+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
    'q+': Math.floor((date.getMonth() + 3) / 3),
    'S': date.getMilliseconds()
  };

  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.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(format(date, 'yyyy-MM-dd HH:mm:ss'));
Copy after login

以上代码中,定义了一个format()函数,该函数接受两个参数:待格式化的日期对象和目标格式。在函数体内,使用正则表达式匹配目标格式中的年、月、日、时、分、秒、季度和毫秒,并将其替换为对应的值。需要注意的是,在替换年时,应该截取年份的后四位数,以避免发生溢出错误。

总结

本文介绍了JavaScript中三种常见的时间格式转换方式:时间戳转日期、日期转时间戳和日期格式化。其中,时间戳是指自1970年1月1日00:00:00以来的秒数,而日期则是JavaScript内置的日期对象。需要注意的是,在进行时间格式转换时,应该注意毫秒和秒的单位差异,以避免发生错误。

The above is the detailed content of javascript to time format. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!