Sometimes we need to calculate the days of two days, or the number of hours, and so on. Use JavaScript to implement this requirement, and then learn some of the JavaScript functions you need to use. Chizhou-Sheng Crafts
The JavaScript program is as follows:
1 |
<script type= "text/javascript" > |
2 |
var getOffDays = function (startDate, endDate) { |
4 |
var mmSec = (endDate.getTime() - startDate.getTime()); |
6 |
return (mmSec / 3600000 / 24); |
8 |
alert(getOffDays( new Date(2009,8,7), new Date(2010,9,17))); |
JavaScript GetTime () method
The GetTime () method returns the total number of milliseconds accumulated since January 1, 1970. Use Dateobject.gettime (), which is used in conjunction with the Date object.
The following program obtains the total number of milliseconds accumulated since January 1, 1970 and outputs it:
1 |
<script type= "text/javascript" > |
3 |
document.write(d.getTime() + " milliseconds since 1970/01/01" ) |
The result of the program operation is:
1 |
1284655348088 milliseconds since 1970/01/01 |
The following program we get the total number of years that have been spent since January 1, 1970 and output it:
01 |
<script type= "text/javascript" > |
09 |
document.write( "It‘s been: " + y + " years since 1970/01/01!" ) |
The result of the program operation is:
1 |
It‘s been: 40.73615794193937 years since 1970/01/01! |
JavaScript Date (date) object
The Date object is used to process dates and times. You can define a Date object by using the New keyword. The following code defines a Date object named MyDate:
The Date object automatically uses the current day and time as its initial value.
By using a method for a Date object, we can easily manipulate the date. In the following example, we set a specific date for the Date object (August 9, 2008):
2 |
myDate.setFullYear(2008,7,9); |
The parameter that represents the month is between 0 and 11. That is, 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 after 5 days:
2 |
myDate.setDate(myDate.getDate()+5); |
If you increase the number of days to change the month or year, the Date object will automatically complete the conversion.
A Date object can also be used to compare two dates. The following code compares the current date with August 9, 2008:
View Source print?
02 |
myDate.setFullYear(2008,7,9); |
06 |
alert( "Today is before 9th August 2008" ); |
10 |
alert( "Today is after 9th August 2008" ); |
Date objects and gettime () methods in JavaScript