JavaScript Date 对象
Date 对象用于处理日期和时间。创建 Data 对象语法如下:
var date_obj = new Date( arg )
arg 为 Data 对象构造函数可选参数。当省略此参数时,Data 对象会自动将当前的日期和时间保存为才初始值。也可以指定 arg 参数来设定 Date 对象的日期与时间值,可以接受的参数如下:
参数格式 | 参数说明与例子 |
---|---|
milliseconds | 数字格式,表示 1970 年 1月 1 日 0 时 到该数字的毫秒数 new Date( 1289403980906 ) |
datestring | 字符串表示的日期与时间,省略时间则默认为 0 点 new Date( "Mar 04, 2012 22:15:14" ) |
year, month | 4位数字的年份,0-11 分别表示 1-12 月 new Date( 2012, 3 ) |
year, month, day | day 用 1-31 表示月中的某天 new Date( 2012, 3, 4 ) |
year, month, day, hours | hours 用 0-23 表示一天中的24小时 new Date( 2012, 3, 4, 22 ) |
year, month, day, hours, minutes | minutes 用 0-59 表示分钟数 new Date( 2012, 3, 4, 22, 15 ) |
year, month, day, hours, minutes, seconds | seconds 用 0-59 表示秒数 new Date( 2012, 3, 4, 22, 15, 14 ) |
year, month, day, hours, minutes, seconds, microseconds | microseconds 用 0-999 表示毫秒数 new Date( 2012, 3, 4, 22, 15, 14, 100 ) |
Date 对象例子
<script type="text/javascript"> var d = new Date(); document.write("现在是:" + d); </script>
运行该例子,输出:
现在是:Sun Mar 04 22:15:14 2012
但在较低 IE 版本(小于8)下,输出结果会包含时区信息:
现在是:Sun Mar 4 22:15:14 UTC+0800 2012
如果您只是单纯的想输出 Date 对象信息而又不想包含时区信息,可以不用创建对象而直接输出:
document.write( Date() );
Date 对象格式化为本地时间
Date 对象提供的 toLocaleString 方法可以方便的将日期和时间转化为本地格式:
<script type="text/javascript"> var d = new Date(); document.write("现在是:" + d.toLocaleString() ); </script>
运行该例子,输出:
现在是:2012年3月4日 22:15:14
本章节内容共分 17 部分:
- JavaScript Date 对象(日期与时间)
- JavaScript Date getFullYear 方法:取得 4 位数字的年份
- JavaScript Date getMonth 方法:取得表示月份的数字
- JavaScript Date getDate 方法:取得月份中的某天
- JavaScript Date getDay 方法:取得一周的某天
- JavaScript Date getHours 方法:取得时间中的小时
- JavaScript Date getMinutes 方法:取得时间中的分钟
- JavaScript Date getSeconds 方法:取得时间中的秒数
- JavaScript Date getMilliseconds 方法:取得时间中的毫秒
- JavaScript Date getTime 方法:取得时间戳(距1970年1月1日的毫秒数)
- JavaScript Date getTimezoneOffset 方法:计算格林威治时间与本地时间的时差
- JavaScript Date parse 方法:将时间字符串转换为时间戳(毫秒)
- JavaScript Date 设置年月日:setFullYear、setMonth 与 setDate 方法
- JavaScript Date 设置时分秒毫秒:setHours、setMinutes、setSeconds 与 setMilliseconds 方法
- JavaScript Date toString 方法:将 Date 对象转换为字符串
- JavaScript Date toDateString 与 toTimeString 方法
- JavaScript Date toLocaleString 方法:将 Date 对象转化为本地化格式显示