Introduction to JavaScriptDate Date and Time object_basic knowledge-js tutorial

Source: Internet
Author: User
This article mainly introduces the date and time objects of JavaScriptDate. For more information, see Date and Time object

1. Introduction

Date object, which is the object that operates on the Date and time. The Date object can only operate on the Date and time through methods.

2. Constructor

2.1 new Date (): returns the current local Date and time.
Parameter: None

Return Value:

{Date} returns a Date object that represents the local Date and time.

Example:

The Code is as follows:


Var dt = new Date ();
Console. log (dt); // => return a Date object that represents the local Date and time.

2.2 new Date (milliseconds): converts the number of milliseconds to the Date object.
Parameters:

① Milliseconds {int}: Number of milliseconds, indicating the number of milliseconds starting from '2014/1/01 00:00:00.

Note: the start time, minute, and second must be added to the current time zone. The Beijing Time Zone is East 8, and the start time is actually '2017/01 08:00:00'

Return Value:

{Date} returns a superimposed Date object.

Example:

The Code is as follows:


Var dt = new Date (1000*60*1); // The number of milliseconds before 1 minute
Console. log (dt); // >{date }:1970/01/01 08:01:00
Dt = new Date (-1000*60*1); // regressing the number of milliseconds in one minute
Console. log (dt); // >{date }:1970/01/01 07:59:00

2.3 new Date (dateStr): converts a string to a Date object.
Parameters:

① DateStr {string}: string that can be converted to a Date object (time can be omitted). There are two main types of string formats:

1) yyyy/MM/dd HH: mm: ss (recommended): if the time is omitted, the returned Date object time is 00:00:00.

2) yyyy-MM-dd HH: mm: ss: if the time is omitted, the returned Date object time is 08:00:00 (plus the local time zone ). If no time is omitted, this string will fail to be converted in IE!

Return Value:

{Date} returns a converted Date object.

Example:

The Code is as follows:


Var dt = new Date ('2014/1/25'); // yyyy/MM/dd
Console. log (dt); // >{date }:2014/12/25 00:00:00
Dt = new Date ('2014/1/25 12:00:00 '); // yyyy/MM/dd HH: mm: ss
Console. log (dt); // >{date }:2014/12/25 12:00:00
Dt = new Date ('1970-12-25 '); // yyyy-MM-dd
Console. log (dt); // =>{ Date}: 08:00:00 (with the time zone of the East 8 area added)
Dt = new Date ('2017-12-25 12:00:00 '); // yyyy-MM-dd HH: mm: ss (Note: This conversion method will report an error in IE !)
Console. log (dt); // >{date }:2014-12-25 12:00:00

2.4 new Date (year, month, opt_day, opt_hours, opt_minutes, opt_seconds, opt_milliseconds): converts year, month, day, And hour to Date objects.
Parameters:

① Year {int}: year; 4 digits. For example, 1999 and 2014

② Month {int}: month; 2 digits. It starts from 0, and 0 indicates February and 11 indicates February.

③ Opt_day {int} (optional): No.; 2 digits; starts from 1, and 1 indicates no. 1.

④ Opt_hours {int} Optional: hour; 2 digits; value range: 0 ~ 23.

⑤ Opt_minutes {int} (optional): minute, two-digit number; value range: 0 ~ 59.

⑥ Opt_seconds {int} (optional) seconds; 2 unnumbered; value range: 0 ~ 59.

7 opt_milliseconds {int} Optional: millisecond; value range: 0 ~ 999.

Return Value:

{Date} returns a converted Date object.

Example:

The Code is as follows:


Var dt = new Date (2014, 11); // December 2014 (the number of the month entered here is 11)
Console. log (dt); // >{date }:2014/12/01 00:00:00
Dt = new Date (2014, 11, 25); // January 1, December 25, 2014
Console. log (dt); // >{date }:2014/12/25 00:00:00
Dt = new Date (2014, 11, 25, 15, 30, 40); //, January 1, 40 seconds
Console. log (dt); // >{date }:2014/12/25 15:30:40
Dt = new Date (2014, 12, 25); // February 13-25 (the number of months entered here is 12, indicating the first month, which is redirected to the second year of February 25, 13th)
Console. log (dt); // =>{ Date}: 2015/01/25

3. Attributes

None; the Date object can only operate on the Date and time through methods.

4. instance method

The Date object instance method can be divided into two forms: local time and UTC time. The same method usually has these two time format operations (the method name is UTC, that is, the Operation UTC time). Here we mainly introduce the operations on the local time.

4.1 get Method
4.1.1 getFullYear (): return the Year Value of the Date object; 4-digit year.

4.1.2 getMonth (): returns the month value of the Date object. Starting from 0, so the real month = return value + 1.

4.1.3 getDate (): returns the Date value in the month of the Date object. The value range is 1 ~ 31.

4.1.4 getHours (): returns the hour value of the Date object.

4.1.5 getMinutes (): returns the minute value of the Date object.

4.1.6 getSeconds (): returns the second value of the Date object.

4.1.7 getMilliseconds (): returns the millisecond value of the Date object.

4.1.8 getDay (): returns the week value of the Date object in a week. 0 indicates Sunday, 1 indicates Monday, 2 indicates Tuesday, and so on.

4.1.9 getTime (): returns the millisecond value between the Date object and '2014/1/01 00:00:00 '(Beijing Time Zone is East 8, and the start time is actually: '2014/1/01 08:00:00 ').

Example:

The Code is as follows:


Dt. getFullYear (); // => 2014: Year
Dt. getMonth (); // => 11: month; actual month (month starts from 0)
Dt. getDate (); // => 25: Day
Dt. getHours (); // => 15: hour
Dt. getMinutes (); // => 30: minute
Dt. getSeconds (); // => 40: seconds
Dt. getMilliseconds (); // => 333: milliseconds
Dt. getDay (); // => 4: the value of the day of the week
Dt. getTime (); // => 1419492640333: returns the millisecond value between the Date object and '2014/1/01 00:00:00 '(the time zone of Beijing time is East 8, and the actual start time is: '2014/1/01 08:00:00 ')

4.2 set Method
4.2.1 setFullYear (year, opt_month, opt_date): Set the year Value of the Date object; 4-digit year.

4.2.2 setMonth (month, opt_date): Set the month value of the Date object. 0 indicates January 1, January, and 11 indicates January 1, December.

4.2.3 setDate (date): set the Date value in the month of the date object. The value range is 1 ~ 31.

4.2.4 setHours (hour, opt_min, opt_sec, opt_msec): Set the hour value of the Date object.

4.2.5 setMinutes (min, opt_sec, opt_msec): sets the minute value of the Date object.

4.2.6 setSeconds (sec, opt_msec): sets the second value of the Date object.

4.2.7 setMilliseconds (msec): sets the millisecond value of the Date object.

Example:

The Code is as follows:


Var dt = new Date ();
Dt. setFullYear (2014); // => 2014: Year
Dt. setMonth (11); // => 11: month; actual month (the month starts from 0)
Dt. setDate (25); // => 25: Day
Dt. setHours (15); // => 15: hour
Dt. setMinutes (30); // => 30: minute
Dt. setSeconds (40); // => 40: seconds
Dt. setMilliseconds (333); // => 333: millisecond
Console. log (dt); // => January 1, December 25, 2014 minutes, 40 seconds, 333 milliseconds

4.3 Other Methods
4.3.1 toString (): Convert Date to a 'year, month, day, hour, minute, second 'string

4.3.2 toLocaleString (): converts a Date to a local format string of 'Year, month, day, hour, minute, second '.

4.3.3 toDateString (): Convert Date to a 'year, month, and Day' string

4.3.4 toLocaleDateString (): converts a Date to a local string of the 'Year, month, and Day' format.

4.3.5 toTimeString (): converts a Date to a 'hour, minute, and second 'string.

4.3.6 toLocaleTimeString (): converts a Date to a local string in 'hour, minute, second 'format.

4.3.7 valueOf (): Same as getTime (), return the millisecond value between the Date object and '2014/1/01 00:00:00 '(the time zone of Beijing time is East 8, and the actual start time is: '2014/1/01 08:00:00 ')

Example:

The Code is as follows:


Var dt = new Date ();
Console. log (dt. toString (); // => Tue Dec 23 2014 22:56:11 GMT + 0800 (China Standard Time): Convert Date to a 'year, month, day, hour, minute, second 'string
Console. log (dt. toLocaleString (); // => December 23, 2014 10:56:11: Convert Date to a local format string of 'Year, month, day, minute, second'
Console. log (dt. toDateString (); // => Tue Dec 23 2014: Convert Date to a 'year, month, and Day' string
Console. log (dt. toLocaleDateString (); // => January 1, December 23, 2014: Convert Date to a local format string of 'Year, month, and Day'
Console. log (dt. toTimeString (); // => 22:56:11 GMT + 0800 (China Standard Time): converts a Date to a 'hour, minute, second 'string
Console. log (dt. toLocaleTimeString (); // => 10:56:11 pm: Convert Date to a local string of 'hour, minute, second'
Console. log (dt. valueOf (); // => returns the millisecond value between the Date object and '2014/1/01 00:00:00 '(the time zone of Beijing time is East 8, and the actual start time is: '2014/1/01 08:00:00 ')

5. Static Method

5.1 Date. now ()
Note: return the millisecond value between the current Date object and '2014/1/01 00:00:00 '(Beijing Time Zone is East 8, and the actual start time is: '2014/1/01 08:00:00 ')

Parameter: None

Return Value:

{Int}: the number of milliseconds between the current time and the start time.

Example:

The Code is as follows:


Console. log (Date. now (); // = & gt; 1419431519276

5.2 Date. parse (dateStr)
Description: converts a string to a Date object, and then returns the millisecond value between the Date object and '2014/1/01 00:00:00 '(the time zone of Beijing time is East 8, and the actual start time is: '2014/1/01 08:00:00 ')

Parameters:

① DateStr {string}: string that can be converted to a Date object (time can be omitted). There are two main types of string formats:

1) yyyy/MM/dd HH: mm: ss (recommended): if the time is omitted, the returned Date object time is 00:00:00.

2) yyyy-MM-dd HH: mm: ss: if the time is omitted, the returned Date object time is 08:00:00 (plus the local time zone ). If no time is omitted, this string returns NaN (not a number) in IE )!

Return Value:

{Int} returns the number of milliseconds between the converted Date object and the start time.

Example:

The Code is as follows:


Console. log (Date. parse ('2014/1/25 12:00:00 '); // => 2014/12
Console. log (Date. parse ('2017-12-25 12:00:00 '); // => 2014 (Note: This conversion method returns NaN in IE !)

6. Actual Operation

6.1 convert the DateTime type of C # To the Date object of Js
Description: The DateTime type of C # is returned to the foreground through Json serialization in the format of "\/Date (1419492640000 )\/". The number in the middle, indicating the number of milliseconds between the DateTime value and the start time.

Example:

Background code: simple ashx

The Code is as follows:


Public void ProcessRequest (HttpContext context ){
System. Web. Script. Serialization. JavaScriptSerializer js = new System. Web. Script. Serialization. JavaScriptSerializer ();
DateTime dt = DateTime. Parse ("15:30:40 ");
String rs = js. Serialize (dt); // Serialize to Json
Context. Response. ContentType = "text/plain ";
Context. Response. Write (rs );
}

Front-end code:

The Code is as follows:


Var dateTimeJsonStr = '\/Date (1419492640000) \/'; // C # Json format of DateTime type conversion
Var msecStr = dateTimeJsonStr. toString (). replace (// Date \ ([-]? \ D +) \ // gi, "$1"); // => '000000': Obtain the millisecond string through regular expression replacement.
Var msesInt = Number. parseInt (msecStr); // converts a millisecond string to a value.
Var dt = new Date (msesInt); // initialize the Date object
Console. log (dt. toLocaleString (); // => December 25, 2014 3:30:40

6.2 get countdown
Note: calculates the time difference between the current time and the target time.

Example:

The Code is as follows:


/**
* Return countdown
* @ Param dt {Date}: Target Date object
* @ Return {Strin}: return countdown: X days X hours X minutes
*/
Function getDownTime (dt ){
// 1. Get the countdown
Var intervalMsec = dt-Date. now (); // the target time minus the current time to obtain the millisecond difference between the two.
Var intervalSec = intervalMsec/1000; // convert to seconds
Var day = parseInt (intervalSec/3600/24); // Number of days
Var hour = parseInt (intervalSec-day x 24*3600)/3600); // hour
Var min = parseInt (intervalSec-day * 24*3600-hour * 3600)/60); // minute

// 2. if the difference in milliseconds is less than 0, it indicates that the target time is less than the current time. At this time, all values are negative:-X days-hour-minute, only the negative number of days is displayed.
If (intervalMsec <0 ){
Hour = 0-hour;
Min = 0-min;
}

// 3. concatenate the string and return it
Var rs = day + 'day' + hour + 'hour + min +' minute ';
Return rs;
}

// Current time:
Console. log (getDownTime (new Date ('2014/1/01'); // => 2015/06 days
Console. log (getDownTime (new Date ('2014/1/01'); // =>-2014/01 days

6.3 compare the size of two Date objects
Note: We can compare the milliseconds between the two and the start time to differentiate the size.

Example:

The Code is as follows:


Var dt1 = new Date ('2014/1/01 ');
Var dt2 = new Date ('2014/1/25 ');
Console. log (dt1> dt2); // => false

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.