javaScript的日期对象

日期对象的创建

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

创建Date对象的语法:

var myDate=new Date()

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

日期对象的方法

方法名 作用
getFullYear() 从 Date 对象以四位数字返回年份。
getMonth() 从 Date 对象返回月份 (0 ~ 11)。
getDate() 从 Date 对象返回一个月中的某一天 (1 ~ 31)。
getDay() 从 Date 对象返回一周中的某一天 (0 ~ 6)。其中:0表示周日,1~6周一到周六
getHours() 返回 Date 对象的小时 (0 ~ 23)。
getMinutes() 返回 Date 对象的分钟 (0 ~ 59)。
getSeconds() 返回 Date 对象的秒数 (0 ~ 59)。
getMilliseconds() 返回 Date 对象的毫秒(0 ~ 999)。
getTime() 返回 1970 年 1 月 1 日至今的毫秒数。类似于Java中的System.currentTimeMillis()
toLocaleString() 根据本地时间格式,把 Date 对象转换为字符串。

案例:输出现在的时间

需求:在浏览器上输出现在的时间

效果:

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>当前时间</title>
</head>
<body>
<script>
    document.write("现在的时间是:" + new Date() + "<hr/>");
    document.write("现在的时间是:" + new Date().toLocaleString() + "<hr/>");
</script>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/guoyx/p/12910441.html