The date object of JavaScript dates the date value of the operation time

Source: Internet
Author: User
Tags diff time and date






Create a Date object:


var objdate=new Date ([arguments list]);


I have summarized the following 3 types of parametric forms:


New Date("month dd yyyy hh:mm:ss");//hh:mm:ss is optional (the default start time is not selected), and the order of the first three items can be arbitrary, even after each field Can add a comma
New Date (yyyy, mth, dd, hh, mm, ss); / / except the first two fields (year, month field), the rest are optional (when not selected, the default is to start), but , the order here is best not to change at random
The new Date(ms);// parameter indicates the number of milliseconds between the time that needs to be created and the GMT time between January 1, 1970. The meaning of the various functions is as follows:


Month: The name of the months in English, from January to December



MTH: The month is represented by an integer, from (January) to 11 (December)



DD: Represents the day ordinal of one months, from 1 to 31



YYYY: four-digit year



HH: Hours, from 0 (midnight) to 23 (11 o'clock in the evening)



MM: Number of minutes, integers from 0 to 59



SS: Number of seconds, integers from 0 to 59



MS: Number of milliseconds, integer greater than or equal to 0



dates in JavaScript (date)



A Date object that is used to manipulate dates and times.



—————————————————————————–



Define a Date Object



Use the keyword new to define a Date object, as shown in the following example, to define an object named MyDate:


var mydate=new Date ()


Note: The date object automatically takes the current date and time as the initial value.



Working with dates



You can easily manipulate dates by using the functions of the Date object.



In the following example, we set a Date object to a specified date value (July 20, 2016):


var mydate=new Date () mydate.setfullyear (2016,7,20)


In the following example, we set the value of MyDate to 5 days later:


var mydate=new Date () mydate.setdate (Mydate.getdate () +5)


Note: If you enter another one months or a year after 5 days, the Date object is automatically processed.



———————————————————————————



Comparison of dates



Use the Date object to compare dates. The following example compares today's date with July 20, 2016:



var mydate=new Date ()



Mydate.setfullyear (2016,7,20) var today = new Date ()



if (mydate>today)



Alert ("Not today until July 20, 2016")



Else



Alert ("Today has passed July 20, 2016")



——————————————————————————–



Example: displaying the current date and time


<html>
<body><script type="text/javascript">
document.write(Date())
</script>
</body>
</html>


Example: getTime() function


Use the getTime() function to calculate how many years have elapsed since 1970


<html>
<body><script type="text/javascript">
var minutes = 1000*60
var hours = minutes*60
var days = hours*24
var years = days*365
var d = new Date()
var t = d.getTime()
var y = t/years
document.write("It’s been: " + y + " years since 1970/01/01!")
</script>
</body>
</html>


Example: function setFullYear()

Use the setFullYear() function to set a date


<html>
<body><script type="text/javascript">
var d = new Date()
d.setFullYear(1992,10,3)
document.write(d)
</script>
</body>
</html>


Example: Function toUTCString()

Convert today's date to a string using the toUTCString() function


<html>
<body><script type="text/javascript">
var d = new Date()
document.write (d.toUTCString())
</script>
</body>
</html>


Example: function getDay()

Use the getDay() function and an array to write the day of the week


<html>
<body><script type="text/javascript">
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"
document.write("Today it is " + weekday[d.getDay()])
</script>
</body>
</html>


Example: Display a clock


<html>
<head>
<script type="text/javascript">
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<10
m=checkTime(m)
s=checkTime(s)
document.getElementById('txt').innerHTML=h+":"+m+":"+s
t=setTimeout('startTime()' ,500)
}function checkTime(i)
{
if (i<10)
{i="0" + i}
return i
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>


Javascript date object Date operation time date value


Manipulating time and date values with JavaScript date objects
A tricky part of software development is the use of time and date values; it seems that each language or each platform has its own format. In the web development process, you can use server-side code to manipulate dates. You can also use JavaScript Date objects to achieve the same purpose. In today's column, we will take a closer look at this object.

Date of use

Using time and date values in JavaScript is very simple. This starts with an instance of the creation date object:

var d = new Date(); 
This will return an instance of the date object in the variable d using the current date and time. This date object includes several methods and properties for accessing and manipulating its values. The following list lists the methods used to access date values:

getDate(): Returns the date in the month.
getDay(): Returns the day of the week. It starts every Saturday (0-6).
getFullYear(): Returns the four-digit year.
getMonth(): Returns the month.
getYear(): Returns the year of two digits.
getUTCDate(): Returns the date in the month according to Coordinated Universal Time (UTC).
getUTCMonth(): Returns the month according to Coordinated Universal Time (0-11).
getUTCFullYear(): Returns a four-digit year based on Coordinated Universal Time.
Note: Wikipedia defines Coordinated Universal Time as a high-precision atomic time standard that is roughly equivalent to Universal Time (UT).

One thing to note about JavaScript and dates is that it uses the number of milliseconds since midnight on January 1, 1970 to save the date. This is called an epoch, and any date and time before this date is not allowed.

As explained in Listing A, using the methods in the previous list is straightforward. You need to be aware that the values for dates and days of the week are zero-based, so you need to add a value to them to display their true values. You can easily use an array to display the day of the week. Listing B is the JavaScript code.

You are not restricted to only use the current date. The date object can be initialized with the value passed to it, like this:
var d = new Date("date value");


In this way, we can modify the previous example to use a specific date. Listing C represents a simple way to find the weekday of a given value. The code will produce the following result:

Today is: Wednesday 4/15/1979
UTC is: Wednesday 4/15/1979

In fact, there are four ways to create a date object instance:


var d = new Date();
var d = new Date(′July 4, 1976′);
var d = new Date(7, 4, 1976);
var d = new Date(7, 4, 1976, 12,00,00);



We have already talked about the first two (note that single quotes or parentheses may be used). The last two use separate integer parameters (time is optional) in the following format:


var d = new Date(month, day, year, hour, minutes, seconds);


Another way to populate a date object is to use the setDate method. It provides a way to reset the value of a date object or initialize it, but this requires a real JavaScript date object:


Var d1 = new Date();
var d2 = new Date("7/4/1976");
d1.setDate(d2.getDate());


getHours(): Returns the hour portion of the time.
getMinutes(): Returns the minute part of the time.
getSeconds(): Returns the second part of the time.
getMilliseconds(): Returns the millisecond portion of the time.
getTime(): Returns the number of milliseconds since midnight on January 1, 1970.
getTimezoneOffset(): Returns the difference between the local time and the Gurney Mean Time (GMT).
getUTCHours(): The hour portion of the return time according to Coordinated Universal Time.
getUTCMinutes(): The minute part of the return time according to Coordinated Universal Time.
getUTCSeconds(): The second part of the return time according to Coordinated Universal Time.
getUTCMilliseconds(): The millisecond portion of the return time according to Coordinated Universal Time.
As mentioned earlier, you can initialize the date object by passing hours, minutes, and seconds, but the millisecond property is set by the setMilliseconds method. The following JavaScript code will show the current time:


<script language="javascript">
var d = new Date();
document.write(d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + ":" + d.getMilliseconds());
document.write(d.getTime());
</script>

It will display the following output:

12:36:33:41
1146760593041

The second value is a bit strange because it shows the number of milliseconds since midnight on January 1, 1970 to the value stored in the date object being referenced. This is useful when looking for differences between two values. For date values, there is also a setTime method that can be used:

Var dt1 = new Date();
var dt2 = new Date(1970, 4, 15);
dt1.setTime(dt2.getTime());
 


Setting properties

Just like the setTime, setDate, and setMilliseconds methods, there are ways to populate all parts of a date object. This includes the following:

setFullYear
setHours
setMinutes
setMilliseconds
setMonth
setSeconds
setUTCFullYear
setUTCMonth
setUTCHours
setUTCSeconds
setUTCMilliseconds
These methods allow you to easily reset the date attribute by passing a new value. Being able to use and display dates is great, but sometimes you need to calculate the date and time.

The simplest calculation is the addition or subtraction of two numbers (you may not agree with this view), so finding the difference between two JavaScript date values is very simple. You just have to find this difference and return it as a number. The result is a date value in milliseconds, so you must divide to get the type of value you want (days, months, minutes, hours, etc.).

The following JavaScript code is used to calculate the number of days to a date. It subtracts the two date values (by getTime) and divides the result by the number of milliseconds in a day (86400000), and finally gets the number of days:

<script type="text/javascript">
var d1 = new Date();
var d2 = new Date(2006, 6, 7);
var day = 1000*60*60*24;
var diff = Math.ceil((d2.getTime()-d1.getTime())/(day));
document.write("Days until vacation: " + diff);
</script>



Date calculation

The required values are added or subtracted using the corresponding attributes, and various attributes of the date value can be increased or decreased. For example, if you want to increase the value by one month, then you have to add one to the month value. The example in Listing D shows the difference between yesterday and today in the previous script. Here is the result of the output:

Days until vacation: 50
Tomorrow it will be 49 days until vacation.
Yesterday, it was 51 days until vacation.

it's time

The use of date and time values has its own limitations, which vary from platform to platform, while web development does not make a difference. The JavaScript date object provides an easy way to use date and time values, but there are still things to keep in mind, such as the numbering of seven days and months of the week, and the format of some methods. Once you get used to it, they are not difficult to remember. One important thing to remember is that the accuracy of the date or event depends on the clock on the computer viewing the page.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.