JavaScript Date(日期) 对象


JavaScript Date(日期) 对象

在JavaScript中,Date对象用于处理日期和时间。该对象兼容大多数Web浏览器,包括Chrome,Firefox和Internet Explorer。

创建日期

用JavaScript创建Date对象有多种方法。

1. new Date()

最简单的方法是使用new操作符和Date()构造函数创建Date对象。 Date对象将创建一个与当前日期和时间匹配的对象。

var currentDate = new Date();

2. new Date(milliseconds)

还可以通过传递自1970年1月1日0时起的毫秒数来创建Date对象。

var birthday = new Date(864000000000);

3. new Date(dateString)

可以使用字符串创建Date对象。

var date = new Date("January 1 2020");

4. new Date(year,month,day,hours,minutes,seconds,milliseconds)

也可以传递年、月、日、小时、分钟、秒、毫秒等值来创建Date对象。

var date = new Date(2020,0,1,0,0,0,0);

方法

Date对象支持许多方法用于访问和处理日期和时间。

1. getDate()

返回一个月中的某一天,为1到31的整数。

var currentDate = new Date();
var day = currentDate.getDate();

2. getDay()

返回星期几,为0到6之间的整数。

var currentDate = new Date();
var dayOfWeek = currentDate.getDay();

3. getFullYear()

返回年份,为4位数的整数。

var currentDate = new Date();
var year = currentDate.getFullYear();

4. getHours()

返回小时,为0到23之间的整数。

var currentDate = new Date();
var hours = currentDate.getHours();

5. getMilliseconds()

返回毫秒,为0到999之间的整数。

var currentDate = new Date();
var milliseconds = currentDate.getMilliseconds();

6. getMinutes()

返回分钟,为0到59之间的整数。

var currentDate = new Date();
var minutes = currentDate.getMinutes();

7. getMonth()

返回月份,为0到11之间的整数。

var currentDate = new Date();
var month = currentDate.getMonth();

8. getSeconds()

返回秒,为0到59之间的整数。

var currentDate = new Date();
var seconds = currentDate.getSeconds();

9. getTime()

返回1970年1月1日0时至当前日期所经过的毫秒数。

var currentDate = new Date();
var time = currentDate.getTime();

10. setDate(day)

将日期改为给定的日期。

var currentDate = new Date();
currentDate.setDate(15);

11. setFullYear(year)

将年份改为给定的年份。

var currentDate = new Date();
currentDate.setFullYear(2020);

12. setHours(hours)

将小时改为给定的小时。

var currentDate = new Date();
currentDate.setHours(10);

13. setMilliseconds(milliseconds)

将毫秒值改为给定的毫秒值。

var currentDate = new Date();
currentDate.setMilliseconds(500);

14. setMinutes(minutes)

将分钟值改为给定的分钟值。

var currentDate = new Date();
currentDate.setMinutes(30);

15. setMonth(month)

将月份改为给定的月份。

var currentDate = new Date();
currentDate.setMonth(11);

16. setSeconds(seconds)

将秒数改为给定的秒数。

var currentDate = new Date();
currentDate.setSeconds(45);

17. setTime(milliseconds)

将日期设置为从1970年1月1日0时起的毫秒数。

var currentDate = new Date();
currentDate.setTime(864000000000);

结论

JavaScript的Date对象允许开发人员轻松处理日期和时间,包括创建日期和时间、获得日期和时间的各个部分,以及修改日期和时间。 但需要注意,Date对象在处理时间时,会受时区影响,需要开发者谨慎处理,防止出现错误。