首页 > 语言 > JavaScript > 正文

浅谈JavaScript Date日期和时间对象

2024-05-06 14:48:32
字体:
来源:转载
供稿:网友

Date 日期和时间对象

1. 介绍

  Date对象,是操作日期和时间的对象。Date对象对日期和时间的操作只能通过方法。

2. 构造函数

2.1 new Date() :返回当前的本地日期和时间
参数:无

返回值:

{Date} 返回一个表示本地日期和时间的Date对象。

示例:

代码如下:
var dt = new Date();
console.log(dt); // => 返回一个表示本地日期和时间的Date对象

2.2 new Date(milliseconds) :把毫秒数转换为Date对象
参数:

①milliseconds {int} :毫秒数;表示从'1970/01/01 00:00:00'为起点,开始叠加的毫秒数。

注意:起点的时分秒还要加上当前所在的时区,北京时间的时区为东8区,起点时间实际为:'1970/01/01 08:00:00'

返回值:

{Date} 返回一个叠加后的Date对象。

示例:

代码如下:
var dt = new Date(1000 * 60 * 1); // 前进1分钟的毫秒数
console.log(dt); // => {Date}:1970/01/01 08:01:00
dt = new Date(-1000 * 60 * 1); // 倒退1分钟的毫秒数
console.log(dt); // => {Date}:1970/01/01 07:59:00

2.3 new Date(dateStr) :把字符串转换为Date对象
参数:

①dateStr {string} :可转换为Date对象的字符串(可省略时间);字符串的格式主要有两种:

1) yyyy/MM/dd HH:mm:ss (推荐):若省略时间,返回的Date对象的时间为 00:00:00。

2) yyyy-MM-dd HH:mm:ss :若省略时间,返回的Date对象的时间为 08:00:00(加上本地时区)。若不省略时间,此字符串在IE中会转换失败!

返回值:

{Date} 返回一个转换后的Date对象。

示例:

代码如下:
var dt = new Date('2014/12/25'); // yyyy/MM/dd
console.log(dt); // => {Date}:2014/12/25 00:00:00
dt = new Date('2014/12/25 12:00:00'); // yyyy/MM/dd HH:mm:ss
console.log(dt); // => {Date}:2014/12/25 12:00:00
dt = new Date('2014-12-25'); // yyyy-MM-dd
console.log(dt); // => {Date}:2014-12-25 08:00:00 (加上了东8区的时区)
dt = new Date('2014-12-25 12:00:00'); // yyyy-MM-dd HH:mm:ss (注意:此转换方式在IE中会报错!)
console.log(dt); // => {Date}:2014-12-25 12:00:00

2.4 new Date(year, month, opt_day, opt_hours, opt_minutes, opt_seconds, opt_milliseconds) :把年月日、时分秒转换为Date对象
参数:

①year {int} :年份;4位数字。如:1999、2014

②month {int} :月份;2位数字。从0开始计算,0表示1月份、11表示12月份。

③opt_day {int} 可选:号; 2位数字;从1开始计算,1表示1号。

④opt_hours {int} 可选:时;2位数字;取值0~23。

⑤opt_minutes {int} 可选:分;2位数字;取值0~59。

⑥opt_seconds {int} 可选:秒;2未数字;取值0~59。

⑦opt_milliseconds {int} 可选:毫秒;取值0~999。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选