Get the App
SLTechnology News&Howtos  ›  Development  › 

How does JavaScript handle date and time

Shulou Source: shulou.com Published: 2022-06-01 13:12:08 09月25日 Update

This article mainly introduces JavaScript how to deal with date and time, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

JavaScript Date object

The Date (date) object is used to process date and time.

Define date

Date objects can be defined by the new keyword. The following code defines a Date object named myDate:

Var myDate=new Date ()

Note: the Date object automatically uses the current date and time as its initial value.

Operation date

We can easily manipulate dates by using methods for date objects.

In the following example, we set a specific date for the date object (August 9, 2008):

Var myDate=new Date () myDate.setFullYear (2008 jade 7)

Note: the parameter for the month is between 0 and 11. If you want to set the month to August, the parameter should be 7.

In the following example, we set the date object to a date 5 days later:

Var myDate=new Date () myDate.setDate (myDate.getDate () + 5)

Note: if increasing the number of days changes the month or year, the date object automatically completes the conversion.

Compare date

The date object can also be used to compare two dates.

The following code compares the current date with August 9, 2008:

Var myDate=new Date (); myDate.setFullYear (2008 new Date 7); var today = new Date (); if (myDate > today) {alert ("Today is before 9th August 2008");} else {alert ("Today is after 9th August 2008");}

Returns the date and time of the day

[xss_clean] (Date ())

GetTime ()

Var d=new Date (); [xss_clean] ("has passed since 1970-01-01" + d.getTime () + "milliseconds")

Note: getTime () returns the number of milliseconds since January 1, 1970.

SetFullYear ()

Var d = new Date () d.setFullYear (1992) [xss_clean] (d)

Note: use setFullYear () to set a specific date.

ToUTCString ()

Var d = new Date () [xss_clean] (d.toUTCString ())

Note: use toUTCString () to convert the date of the day (based on UTC) to a string.

GetDay ()

Var d=new Date () var weekday=new Array (7) weekday [0] = "Sunday" weekday [1] = "Monday" weekday [2] = "Tuesday" weekday [3] = "Wednesday" weekday [4] = "Thursday" weekday [5] = "Friday" weekday [6] = "Saturday" [xss_clean] ("Today is" + weekday [d.getDay ()])

Note: use getDay () and arrays to display days of the week, not just numbers.

Show current time clock

Function startTime () {var today=new Date () var h=today.getHours () var m=today.getMinutes () var s=today.getSeconds () / / add a zero in front of numbers

Tags: Object date world time character string week month method year comment hour number article part format face code example parameter Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno vpn Shulou Tech Info MySQL macOS