Node.js中 Date 对象使用样例

本文介绍了JavaScript中Date对象的创建方式及使用方法,包括通过不同构造函数初始化Date对象,并详细讲解了如何提取和设置日期时间的各个组成部分。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Date对象

     Date 对象用于处理日期和时间。

创建 Date 对象

1)  默认初始化方法. 例如: 

var theDate = new Date();

Date 对象会自动把当前日期和时间保存为其初始值。

2) 使用标准的日期格式字符串初始化. 例如: 

var myDate = new Date("2012-02-15 21:00:00");
console.log('Date: ',   myDate );

Results:

Date: Fri Feb 15 2012 21:00:00 GMT+0800 (中国标准时间)

3) 用从1970年1月1日00:00:00 UTC开始计算的毫秒数作为参数初始化. 例如:  

var myDate = new Date(1491313260313);
console.log('Date: ',   myDate );

Results:

Date: Tue Apr 04 2017 21:41:00 GMT+0800 (中国标准时间)

提取、设置Date对象各分量

提取Date对象个分量

var myDate = new Date("2012-02-15 21:00:00");  
console.log( myDate );  

// getFullYear()
// 从 Date 对象返回年。
console.log( "        Year:", myDate.getFullYear() ); 

// getMonth() 
// 从 Date 对象返回月份 (0 ~ 11)。
console.log( "       Month:", myDate.getMonth() ); 

// getDate()
// 从 Date 对象返回一个月中的某一天 (1 ~ 31)。
console.log( "        Date:", myDate.getDate() ); 

// getDay()
// 从 Date 对象返回一周中的某一天 (0 ~ 6)。
console.log( "         Day:", myDate.getDay() ); 

// getHours()
// 返回 Date 对象的小时 (0 ~ 23)。
console.log( "        Hour:", myDate.getHours() ); 

// getMinutes()
// 返回 Date 对象的分钟 (0 ~ 59)。
console.log( "      Minute:", myDate.getMinutes() ); 

// getSeconds()
// 返回 Date 对象的秒数 (0 ~ 59)。
console.log( "      Second:", myDate.getSeconds() ); 

// getMilliseconds()
// 返回 Date 对象的毫秒(0 ~ 999)。
console.log( " Millisecond:", myDate.getMilliseconds() ); 

  Results: 

设置Date对象个分量

var myDate = new Date();

// setFullYear()
// 设置 Date 对象的年。
myDate.setFullYear(2017)

// getMonth() 
// 设置 Date 对象返回月份 (0 ~ 11)。
myDate.setMonth(3)

// setDate()
// 设置 Date 对象返回一个月中的某一天 (1 ~ 31)。
myDate.setDate(10) 

// setHours()
// 设置 Date 对象的小时 (0 ~ 23)。
myDate.setHours(20) 

// setMinutes()
// 设置 Date 对象的分钟 (0 ~ 59)。
myDate.setMinutes(10)

// setSeconds()
// 设置 Date 对象的秒数 (0 ~ 59)。
myDate.setSeconds(12)

// setMilliseconds()
// 设置 Date 对象的毫秒(0 ~ 999)。
myDate.setMilliseconds(123)

console.log( myDate ); 

Results:

Note: 没有 setDay()方法

Reference:

[1] http://www.w3school.com.cn/jsref/jsref_obj_date.asp

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值