您的位置:首页 > Web前端 > JavaScript

javascript学习(3)Date使用

2013-04-10 07:42 183 查看
创建当天日期对象:

var thedate = new Date();

document.write('当前月份是'+thedate.getMonth()+'月');

问题:输出的月份为2,可是当前命名是3月。

原因:javascript中,1月用0表示....12月用11表示,所以3月用2表示,所以上边代码要想输出正确的月份,需要下面的代码。

创建指定日期对象

var thedate = new Date(2012,3,1);

var thedate = new Date('3 mar 2012');

document.write('给定月份是'+thedate.getMonth()+'月');

注意:最后输出的数字为3,参数“2012,3,1”表示2012年4月1号,所以要想输出正确的月份需要+1

一些有用的方法

toDateString():以特定的格式显示日期部分

var thedate = new Date(2012, 2, 1);

document.write(thedate.toDateString());

问题:显示出来的结果,中国人看不懂:

解决方案:使用toLocaleDateString():以本地格式显示日期部分

document.write(thedate.toLocaleDateString());

toTimeString():以特定的格式显示时间部分(小时,分,秒,时区)

var thedate = new Date(2012, 2, 1);

document.write(thedate.toTimeString());

问题:显示出来的小时,分,秒都是0

原因:声明thedate实例时,为给其时间赋值,只是给日期赋值

解决方案:声明Date实例时也指明小时,分,秒

声明带小时,分,秒的Date实例

var thedate = new Date(2012, 2, 1,13,10,02);

document.write(thedate.toTimeString());

问题:带时区

解决方案:使用toLocaleTimeString()方法

var thedate = new Date(2012, 2, 1, 13, 10, 02); document.write(thedate.toLocaleTimeString());

toLocaleString():以本地格式显示日期和时间还有星期几

var thedate = new Date(2012, 2, 1, 13, 10, 02);

document.write(thedate.toLocaleString());

getTime():返回日期的毫秒表示

var thedate = new Date(2012, 2, 1, 13, 10, 02);

document.write(thedate.getTime());

输出结果:1330578602000

这个数字代表什么?距离UTC时间1970年1月1日凌晨12点的毫秒表示,不信可以换算一下,大概是42年零1个月

任何语言中的时间都很重要,所以JavaScript中的时间一定要搞清楚。

千年虫问题:

上世纪,使用两位数存储时间,1987存储为87

2087年和1987年都用87表示,会产生冲突,而且2077可能比1987还要小(77<87)

多国受影响。

闰年虫问题:

地球公转为365天5小时48分46秒

人为规定1年为365天,每年多出来5小时48分46秒

4年就多出来一天,此时地球还未到太阳的指定位置,还差1天的时间才能到

平年2月份28天,闰年在2月份的末尾加上1天,是为29天

计价器没有考虑到闰年的情况,2月28直接跳到3月1日,平白少了1天,税务哪里能干

getYear():获取日期的年份,有些资料上说返回的是年份的后2为,在IE9上测试,返回的是4位,而在Firefox上测试返回的是112()。

getFullYear():返回年份的4为表示形式,经测试在IE和Firefox上返回的都是2012。所以建议使用getFullYear()函数获取年份,而不是getYear()

注:测试代码下面代码var thedate = new Date(2012, 2, 1, 13, 10, 02);

getMonth():返回月份,从0开始,0表示1月

getDate():返回日期中的某天

getDay():返回改日为星期几

getHours():返回日期中的小时值

getMinutes:返回日期中的分钟值

getSeconds():返回日期中的秒值

getMilliseconds():返回日期中的毫秒值

setFullYear():设置当前Date对象的年份为指定年份

var thedate = new Date(2012, 2, 1, 13, 10, 02, 476);

thedate.setFullYear(2013)

document.write(thedate.getFullYear());
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: