Javascript 基础之Date对象

来源:互联网 发布:福州市第一中学 知乎 编辑:程序博客网 时间:2024/06/02 17:36

Date 对象

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

var myDate = new Date();document.write(myDate);// 输出 Wed Jul 20 2016 13:53:15 GMT+0800 (中国标准时间)

Date 对象方法

获得日期值

  1. getDate()

    返回一个月中的某一天 (1 ~ 31)。

    document.write(myDate.getDate());    //输出 20
  2. getDay()

    返回一周中的某一天 (0 ~ 6), 0表示星期日,1表示星期一

    document.write(myDate.getDay());    //输出 3
  3. getMonth()

    从 Date 对象返回月份 (0 ~ 11)。

    document.write(myDate.getMonth());    //输出 6
  4. getFullYear()

    从 Date 对象以四位数字返回年份。

    document.write(myDate.getFullYear());    //输出 2016
  5. toDateString()

    把 Date 对象的日期部分转换为字符串。

    document.write(myDate.toDateString());  //输出 Wed Jul 20 2016

设置日期值

修改Date对象中的日期部分,可以使用一组set方法,与上面的get函数相对应。
在设置日期,月份,的时候,如setMonth(13),会表示下一年的二月。
1. setDate()

设置一个月中的某一天(1 ~ 31)    myDate.setDate(10);//设置10号    document.write(myDate.getDate());//输出 10    document.write("<br/>");    document.write(myDate.getDay());//相应的星期数也要改变
  1. setMonth()

    设置月份—(0 ~ 11)

    myDate.setMonth(5);//设置为5 月份document.write(myDate.getMonth());// 输出 5
  2. setFullYear()

    设置年份(四位数字)

    myDate.setFullYear(1999);//设置为 1999 document.write(myDate.getFullYear()); // 输出 1999

获得时间值

  1. getHours()

    返回 Date 对象的小时 (0 ~ 23)。

    document.write(myDate.getHours());
  2. getMinutes()

    返回 Date 对象的分钟 (0 ~ 59)。

    document.write(myDate.getMinutes());
  3. getSeconds()

    返回 Date 对象的秒数 (0 ~ 59)。

    document.write(myDate.getSeconds());
  4. getMilliseconds()

    返回 Date 对象的毫秒(0 ~ 999)。

    document.write(myDate.getMilliseconds());
  5. toTimeString()

    把 Date 对象的时间部分转换为字符串。

    document.write(myDate.toTimeString());

设置时间值

当设置的小时数,分钟数,秒数,大于规定的时候,javascript会自动向前滚动进行计算。

  1. setHours()

    设置小时(0 ~ 23)

    myDate.setHours(20);
  2. setMinutes()

    设置分钟(0 ~ 59)

    myDate.setMinutes(5);
  3. setSeconds()

    设置秒数(0 ~ 59)

    myDate.setSeconds(45);
  4. setMilliseconds()

    设置毫秒(0 ~ 999)

    myDate.setMilliseconds(555);

Date方法还有一些方法再次不再赘述,有兴趣的可以参考W3C的文档进行查阅!

转载请标明出处!!!!

http://blog.csdn.net/divide_

0 0
原创粉丝点击