我们有时候会需要打印出当前的时间,比如发票上的时间。JS自带了一些函数可以帮我们解决这个问题。
比如:
使用 Date() 方法获得当日的日期:
可以通过 new 关键词来定义 Date 对象。以下代码定义了名为 myDate 的 Date 对象:
注释:Date 对象自动使用当前的日期和时间作为其初始值。
返回当前时间:
输出结果:
同时,还可以转化不同的时间表示方式:
输出结果是:
比如:
使用 Date() 方法获得当日的日期:
document.write(Date())
输出结果:
Tue Aug 19 2014 23:29:39 GMT-0400 (AST)
Date 对象用于处理日期和时间。
可以通过 new 关键词来定义 Date 对象。以下代码定义了名为 myDate 的 Date 对象:
var myDate=new Date()
注释:Date 对象自动使用当前的日期和时间作为其初始值。
返回当前时间:
var dateDigitToString = function (num) {
return num < 10 ? '0' + num : num;
}; //这个函数的作用是把个位数的十位置0,凑成两位数,如:08 04
var currentDate = new Date(),
year = dateDigitToString(currentDate.getFullYear()),
month = dateDigitToString(currentDate.getMonth() + 1),//Date.getMonth()的返回值是0-11,所以要+1
date = dateDigitToString(currentDate.getDate()),
hour = dateDigitToString(currentDate.getHours()),
minute = dateDigitToString(currentDate.getMinutes()),
second = dateDigitToString(currentDate.getSeconds()),
formattedDateString = year + '年' + month + '月' + date + '日 ' + hour + ':' + minute + ':' + second;
document.write(formattedDateString);
输出结果:
2014年08月19日 23:30:36
同时,还可以转化不同的时间表示方式:
document.write(formattedDateString);
document.write("<br /><br />")
document.write(date + "." + month + "." + year)
document.write("<br /><br />")
document.write(year + "/" + month + "/" + date)
输出结果是:
2014年08月19日 23:35:50
19.08.2014
2014/08/19