JavaScript Date Object Usage Summary

Source: Internet
Author: User
Tags getdate local time time and date

creation of a JavaScript date object

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");

The following 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 the fields can be added with commas

New Date (YYYY,MTH,DD,HH,MM,SS);

In addition to the first two fields (the year, month field), the rest are optional (default to start), however, the order is best not to be arbitrarily transformed

New Date (MS);

The parameter represents the number of milliseconds between the time that needs to be created and the GMT time of January 1, 1970. The meanings of the various functions are 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 (January 14, 2010):

var mydate=new Date ()

Mydate.setfullyear (2010,0,14)

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 January 14, 2010:

var mydate=new Date ()

Mydate.setfullyear (2010,0,14) var today = new Date ()

if (mydate>today)

Alert ("Not today until January 14, 2010")

Else

Alert ("Today has passed January 14, 2010")

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

Example: displaying the current date and time

<body><script type= "Text/javascript" >

document.write (Date ())

</script>

</body>

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

Example: GetTime () function

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

<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>

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

Example: function setFullYear ()

Use the setFullYear () function to set a date

<body><script type= "Text/javascript" >

var d = new Date ()

D.setfullyear (1992,10,3)

document.write (d)

</script>

</body>

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

Example: Function toutcstring ()

Use the toutcstring () function to convert today's date to a string

<body><script type= "Text/javascript" >

var d = new Date ()

document.write (d.toutcstring ())

</script>

</body>

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

Example: function Getday ()

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

<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>

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

Example: Displaying a clock

<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>

<body onload= "StartTime ()" >

<div id= "TXT" ></div>

</body>

(Transferred from: Http://www.prglab.com/blog/js-tutorial/js-string Program Lab)

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

manipulate time and date values with JavaScript date objects
A tricky part of software development is the use of time and date values; Each language or platform seems to have its own format. During Web Development, you can use server-side code to manipulate dates, and you can also use JavaScript Dates ( Date ) object for the same purpose. In today's column, we'll take a closer look at this object.

Use Date

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

var d = new Date ();
This returns an instance of a Date object in 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. Starting from Saturday per week (0-6).
getFullYear (): Returns a four-digit year.
GetMonth (): Returns the month.
GetYear (): Returns a double-digit year.
getUTCDate (): According to Coordinated Universal Time (UTCreturns the date in the month.
getUTCMonth (): According to Coordinated Universal Time (0- One) returns the month.
getUTCFullYear (): Returns a four-digit year based on coordinated Universal Time.
Note: Wikipedia (Wikipediadefines the coordinated universal time as a high-precision atomic time standard that is approximately equivalent to the world time (UT).

One thing to note about JavaScript and dates is that it uses from 1970 year 1 months 1 The number of milliseconds since midnight of the day to save the date. This is calledtheepoch, and any dates and times before this date are not allowed.

As Listing a shows, the method of using the previous list is straightforward. You need to note that the date and day of the week values 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. In list B is the JavaScript code.

You are not restricted to using only the current date. A Date object can be initialized with the value passed to it, as follows:

var d = new Date ("Date value");

Using this method, we can modify the previous example to use a specific date. List C represents a simple way to discover the Sunday period of a given value. The code produces 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've already talked about the top two (note that single quotes or parentheses may be used). The last two uses a separate integer parameter (the 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 take advantage of the setDate method. It provides a way to reset the value of a Date object or initialize it, but this requires a true JavaScript Date object:

Var D1 = new Date ();
var d2 = new Date ("7/4/1976");
D1.setdate (D2.getdate ());

There are many more ways to fix the various properties of a Date object, but let's take a look at the time before discussing them.

In addition to the date component, the Date object also holds the time information. The following method provides access to time information for a Date object:

GetHours (): Returns the hour portion of the time.
Getminutes (): Returns the minute part of the time.
Getseconds (): Returns the seconds part of the time.
Getmilliseconds (): Returns the millisecond portion of the time.
GetTime (): Returns since1970years1Month1the number of milliseconds since midnight of the day.
getTimezoneOffset (): Returns the local time and Galini standard Time (GMTminute difference between the.
getUTCHours (): The hourly portion of the time that is returned according to Coordinated Universal Time.
getUTCMinutes (): The minute portion of the time that is returned according to Coordinated Universal Time.
getUTCSeconds (): The second part of the time that is returned according to Coordinated Universal Time.
getUTCMilliseconds (): The millisecond portion of the time that is returned according to Coordinated Universal Time.
As mentioned earlier, you can initialize a date object by passing hours, minutes, and seconds, but the millisecond property is passedsetmillisecondsmethod to set the. The following paragraphJavaScriptThe code displays 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 odd, because it shows the number of milliseconds since 1970 1 months , 1 days, and midnight to the value stored in the referenced date object. This is useful when looking for a difference 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 make it easy for you to reset the date property by passing a new value. It's good to be able to use and display dates, but sometimes you need to calculate dates and times.

The simplest calculation is the addition and subtraction of two numbers (which you might disagree with), so it 's easy to find the difference between the two JavaScript date values. You just have to find the difference and return it as a number. The result is a date value in milliseconds, so you have to divide to get the type of value you want (day, month, minute, hour, and so on).

The following JavaScript code is used to calculate the number of days to a date. It subtracts two date values (via GetTime), and then uses the resulting results in milliseconds (86400000) for a day, 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>

Calculation of dates

The various properties of date values can be increased or decreased by using the corresponding attributes to add and subtract the desired values. For example, if you want to increase the value by one months, then you need to add one to the month value. The example in list 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'll be until vacation.
Yesterday, it was until vacation.

It's time

The use of date and time values has its own limitations, which are different depending on the platform, and Web development is not different. JavaScript 's date objects provide a simple way to use date and time values, but there are still some 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, it's not hard to remember. One important thing to keep in mind is that the accuracy of a date or event depends on the clock on the computer where the page is viewed.

Copyright NOTICE: Welcome reprint, Hope in your reprint at the same time, add the original address, thank you with

JavaScript Date Object Usage Summary

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.