JavaScript Date Object Detailed _javascript tips

Source: Internet
Author: User
Tags getdate instance method local time serialization time and seconds

This article mainly describes the date and time objects of the operation, the specific contents are as follows

Directory
1. Description: Describes the Date object.

2. Constructor: Describes several ways to introduce the constructor of the date object, new Date ().

3. Example method: Introduces the Date object's get, set, and other instance methods.

4. Static method: Describes the static method of the Date object: Date.now (), Date.parse (), and so on.

5. Practice: Introduces some examples of Date objects: getting the countdown, comparing the size of the 2 date objects, and so on.

I. INTRODUCTION
1.1 Description

Date object that is the object of the action date and time. A Date object can operate on dates and times only through methods.

1.2 Properties

None of the date objects can operate on dates and times only through methods.

Two. Constructor function
2.1 New Date (): Returns the current local date and time

Parameters: None

return value:

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

Example:

var dt = new Date ();
Console.log (DT); => returns a Date object that represents the local date and time

2.2 New Date (milliseconds): Converts the number of milliseconds to a Date object

Parameters:

①milliseconds {int}: Number of milliseconds, representing the number of milliseconds to begin stacking from ' 1970/01/01 00:00:00 ' as the starting point.

Note: The time of the beginning of the seconds also add the current time zone, the Times in Beijing East 8 zone, the starting time is actually: ' 1970/01/01 08:00:00 '

return value:

{Date} returns a superimposed date object.

Example:

var dt = new Date (1000 * 60 * 1); Forward 1 minute milliseconds
console.log (DT);//=> {date}:1970/01/01 08:01:00
dt = new Date (-1000 * 60 * 1);//rewind 1 minutes of milliseconds
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}: A string that can be converted to a Date object (can be omitted); There are two main types of strings:

1) yyyy/mm/dd HH:mm:ss (recommended): If you omit the time, the date object returned time is 00:00:00.

2) Yyyy-mm-dd HH:mm:ss: If the time is omitted, the Date object returned is 08:00:00 (plus the local time zone). If you do not omit the time, this string will fail in IE conversion!

return value:

{Date} returns a converted Date object.

Example:

var dt = new Date (' 2014/12/25 '); YYYY/MM/DD
console.log (DT);//=> {DATE}:2014/12/25 00:00:00
dt = new Date (' 2014/12/25 12:00:00 ');//yyyy/ Mm/dd HH:mm:ss
console.log (DT);//=> {DATE}:2014/12/25 12:00:00
 
dt = new Date (' 2014-12-25 ');//yyyy-mm-dd< C5/>console.log (DT); => {date}:2014-12-25 08:00:00 (plus the time zone of East 8)
dt = new Date (' 2014-12-25 12:00:00 ');//Yyyy-mm-dd HH:mm:ss (Note: This conversion In IE will be an error! )
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): convert Date To Date object

Parameters:

①year {int}: year; 4 digits. such as: 1999, 2014

②month {int}: month; 2 digits. Starting from 0, 0 means January, 11 represents December.

③opt_day {int} is optional: number, 2 digits, starting from 1, 1 represents 1th.

④opt_hours {int} optional: time; 2 digits; Value 0~23.

⑤opt_minutes {int} optional: 2 digits; 0~59.

⑥opt_seconds {int} optional: seconds; 2 not digits; 0~59 value.

⑦opt_milliseconds {int} is optional: milliseconds; 0~999 value.

return value:

{Date} returns a converted Date object.

Example:

var dt = new Date (2014, 11); December 2014 (The number of months entered here is one)
console.log (DT);//=> {date}:2014/12/01 00:00:00
dt = new Date (2014, 11, 25);//201 4 year December 25
console.log (DT);//=> {DATE}:2014/12/25 00:00:00
dt = new Date (2014, 11, 25, 15, 30, 40);//December 2014 25th 15:30 40 seconds
console.log (DT);//=> {DATE}:2014/12/25 15:30:40
dt = new Date (2014, 12, 25);//March 25, 2014 (This is lost The number of months entered is 12, which represents the 13th month, and jumps to the second year of January)
console.log (DT);//=> {DATE}:2015/01/25

Three. Instance method
the instance methods of a Date object are divided into 2 main forms: local time and UTC time. In the same way, there are typically 2 time format operations (method names with UTC, or UTC time), which mainly describes the operation of local time.

3.1 Get method

3.1.1 getFullYear (): Returns the year value of the Date object; 4-bit year.

3.1.2 GetMonth (): Returns the month value of a Date object. Starting from 0, so the real month = Returns the value +1.

3.1.3 GetDate (): Returns the date value in the month of the date object, the range of the value 1~31.

3.1.4 GetHours (): Returns a Date object's small value.

3.1.5 getminutes (): Returns the minute value of a Date object.

3.1.6 getseconds (): Returns the number of seconds in a Date object.

3.1.7 getmilliseconds (): Returns the millisecond value of the Date object.

3.1.8 getday (): Returns the week value of the week for the date object, 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on

3.1.9 getTime (): Returns the millisecond value between the Date object and ' 1970/01/01 00:00:00 ' (The time zone in Beijing is East 8, and the starting time is actually: ' 1970/01/01 08:00:00 ').

Example:

Dt.getfullyear (); => 2014: Year
dt.getmonth ();//=> 11: Month; actual for December (month starting from 0)
dt.getdate ();//=> 25: Day
dt.gethours (); /=> 15: Time
dt.getminutes ()//=> 30: Sub
dt.getseconds ();//=> 40: Sec
dt.getmilliseconds ();//=> 333 : Millisecond
dt.getday ();//=> 4: The value of the day of the Week
Dt.gettime ();//=> 1419492640333: Returns the millisecond value between the Date object and ' 1970/01/01 00:00:00 ' ( The time zone in Beijing is East 8, the starting time is actually: ' 1970/01/01 08:00:00 ')

3.2 Set method

3.2.1 setFullYear (year, Opt_month, opt_date): Sets the Date object's age value, 4-bit year.

3.2.2 Setmonth (Month, opt_date): Sets the month value of the Date object. 0 indicates January, 11 represents December.

3.2.3 Setdate (date): Sets the date value in the month of the date object; The range of values 1~31.

3.2.4 sethours (Hour, opt_min, Opt_sec, opt_msec): Sets the Date object's small value.

3.2.5 setminutes (min, Opt_sec, opt_msec): Sets the minute value of the Date object.

3.2.6 setseconds (sec, opt_msec): Sets the number of seconds for the date object.

3.2.7 setmilliseconds (msec): Sets the millisecond value of the Date object.

Example:

var dt = new Date ();
Dt.setfullyear (2014); => 2014: Year
dt.setmonth (one);//=> 11: Month; actual for December (month starting from 0)
dt.setdate;//=> 25: Day
dt.sethours (15); => 15:
dt.setminutes//=> 30: Min
dt.setseconds (s);//=> 40: Sec
dt.setmilliseconds (333); => 333: Millisecond
console.log (DT);//=> December 25, 2014 15:30 40 second 333 ms

3.3 Other methods

3.3.1 toString (): Converts date to a ' date and time ' string

3.3.2 toLocaleString (): Converts date to a local format string with a ' month and a day '

3.3.3 todatestring (): Converts date to a ' month-day ' string

3.3.4 tolocaledatestring (): Converts date to a local format string of ' year/month '

3.3.5 totimestring (): convert date to a ' time and seconds ' string

3.3.6 tolocaletimestring (): convert date to a local format string of ' time and seconds '

3.3.7 valueof (): As with gettime (), returns the millisecond value between the Date object and ' 1970/01/01 00:00:00 ' (The time zone in Beijing is East 8, and the starting time is actually: ' 1970/01/01 08:00:00 ')

Example:

var dt = new Date ();
Console.log (Dt.tostring ());  => Tue Dec 2014 22:56:11 gmt+0800 (China Standard Time): convert date to a ' date and time ' string
console.log (dt.tolocalestring ());//=> December 23, 2014 10:56:11: Converts date to a local format string Console.log (Dt.todatestring ()) with a ' month and a day '
 
;//=> Tue DEC 23 2014: Turn date Change to a ' year and a day ' string
console.log (dt.tolocaledatestring ());//=> December 23, 2014: convert date to a local format string
 
of ' year/month ' Console.log (Dt.totimestring ()); => 22:56:11 gmt+0800 (China Standard Time): convert date to a ' time and seconds ' string
console.log (dt.tolocaletimestring ());//=> 10:56:11 : Converts date to a local format string Console.log (Dt.valueof ()) with a ' time and minutes '
 
;//=> returns the millisecond value between the Date object and ' 1970/01/01 00:00:00 ' (The time zone in Beijing is East 8, The starting time is actually: ' 1970/01/01 08:00:00 ')

Four. Static method
4.1 date.now ()

Description: Returns the millisecond value between the Date object and the ' 1970/01/01 00:00:00 ' (The time zone in Beijing is East 8, and the starting time is actually: ' 1970/01/01 08:00:00 ')

Parameters: None

return value:

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

Example:

Console.log (Date.now ()); => 1419431519276

4.2 Date.parse (DATESTR)

Description: Converts a string to a Date object and returns the millisecond value between this Date object and ' 1970/01/01 00:00:00 ' (The time zone in Beijing is East 8, and the starting time is actually: ' 1970/01/01 08:00:00 ')

Parameters:

①datestr {string}: A string that can be converted to a Date object (can be omitted); There are two main types of strings:

1) yyyy/mm/dd HH:mm:ss (recommended): If you omit the time, the date object returned time is 00:00:00.

2) Yyyy-mm-dd HH:mm:ss: If the time is omitted, the Date object returned is 08:00:00 (plus the local time zone). If you do not omit the time, 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:

Console.log (Date.parse (' 2014/12/25 12:00:00 ')); => 1419480000000
console.log (Date.parse (' 2014-12-25 12:00:00 '));//=> 1419480000000 (Note: This conversion mode is returned in IE nan! )

Five. Actual operation
5.1 C # 's datetime type to the Date object of JS

Description: The datetime type of C # is returned to the foreground by JSON serialization in the format: "\/date (1419492640000) \/". The middle number that represents the number of milliseconds between the value of datetime and the start time.

Example:

Background code: Simple ASHX

public void ProcessRequest (HttpContext context) {
 System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer ();
 DateTime dt = DateTime.Parse ("2014-12-25 15:30:40");
 String rs = js. Serialize (DT); Serialized into a JSON context
 . Response.ContentType = "Text/plain";
 Context. Response.Write (RS);

Foreground code:

var datetimejsonstr = ' \/date (1419492640000) \/'; C # datetime type conversion JSON format
var msecstr = datetimejsonstr.tostring (). replace (/\/date\ ([-]?\d+) \) \//gi, "$"); > ' 1419492640000 ': by regular substitution, get the millisecond string
var msesint = Number.parseint (MSECSTR);//MS String converted to numeric
var dt = new Date (mses INT); Initializes the Date object
Console.log (dt.tolocalestring ());//=> December 25, 2014 3:30:40

5.2 Get the countdown

Description: Calculates the current time from the target time difference how many days.

Example:

/**
* Back
to Countdown * @param dt {Date}: Destination Date object
* @return {Strin}: Back to Countdown: X-day x Time x
/function getdowntime (dt ) {
 //1. Get the countdown to
 var intervalmsec = Dt-date.now ();//target time minus current time, get the difference between the number of milliseconds
 var intervalsec = intervalmsec/ 1000;  Convert to seconds
 var day = parseint (INTERVALSEC/3600/24);//days
 var hour = parseint ((intervalsec-day * 24 * 3600)/ 3600); Hour
 var min = parseint ((intervalsec-day * 3600-hour * 3600)/60);//min/
 
 2. If the difference in milliseconds is less than 0, the destination time is less than the current time , when the value is negative: X-day-time-divided, display, only the number of days before the negative on the line.
 if (Intervalmsec < 0) {
  hour = 0-hour;
  min = 0-min;
 }
 
 3. Concatenation string and returns
 var rs = day + ' days ' + hour + ' when ' + min + ' min ';
 return RS;
}
 
Current time: 2014/12/28 13:26
Console.log (Getdowntime (New Date (' 2015/06/01 '));//=> 154 day 10:33
Console.log (New Date (' 2014/01/01 ')) (getdowntime); =>-361 Days 13:26
 

5.3 Compare the size of 2 date objects

Note: You can compare the number of milliseconds between 2 and the start time to distinguish between sizes.

Example:

var dt1 = new Date (' 2015/12/01 ');
var dt2 = new Date (' 2015/12/25 ');
Console.log (Dt1 > DT2); => false

The above is the entire content of this article, I hope to help you learn.

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.