Date Date and Time Objects
1. Introduction
A Date object is an object that operates on date and time. The operation of the Date object on date and time can only be done through methods.
2. Constructor
2.1 new Date(): Return the current local date and time
Parameters: None
Return value:
{Date} Returns a Date object representing the local date and time.
Example:
The code copy is as follows:
var dt = new Date();
console.log(dt); // => Returns a Date object representing the local date and time
2.2 new Date(milliseconds): convert milliseconds into Date object
parameter:
① milliseconds {int} : milliseconds; represents the number of milliseconds starting from '1970/01/01 00:00:00' as the starting point.
Note: The time, minutes and seconds at the starting point must be added to the current time zone. The time zone of Beijing time is East 8, and the actual starting point time is: '1970/01/01 08:00:00'
Return value:
{Date} Returns an overlayed Date object.
Example:
The code copy is as follows:
var dt = new Date(1000 * 60 * 1); // Number of milliseconds to advance by 1 minute
console.log(dt); // => {Date}:1970/01/01 08:01:00
dt = new Date(-1000 * 60 * 1); // Number of milliseconds to go back 1 minute
console.log(dt); // => {Date}:1970/01/01 07:59:00
2.3 new Date(dateStr): convert strings into Date objects
parameter:
①dateStr {string}: A string that can be converted into a Date object (time can be omitted); there are two main formats of strings:
1) yyyy/MM/dd HH:mm:ss (recommended): If time is omitted, the time of the returned Date object is 00:00:00.
2) yyyy-MM-dd HH:mm:ss: If time is omitted, the time of the returned Date object is 08:00:00 (plus the local time zone). If time is not omitted, this string will fail to convert in IE!
Return value:
{Date} Returns a converted Date object.
Example:
The code copy is as follows:
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
console.log(dt); // => {Date}:2014-12-25 08:00:00 (Add to the time zone of East 8)
dt = new Date('2014-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): convert year, month, day, hour, minute and second into Date objects
parameter:
①year {int}: year; 4 digits. For example: 1999, 2014
②month {int}: month; 2 digits. Calculated from 0, 0 means January and 11 means December.
③opt_day {int} optional: number; 2-digit number; start from 1, 1 represents number 1.
④opt_hours {int} optional: time; 2-digit number; value 0~23.
⑤opt_minutes {int} Optional: points; 2-digit numbers; values 0~59.
⑥opt_seconds {int} Optional: seconds; 2 unnumbered; values 0~59.
⑦opt_milliseconds {int} Optional: milliseconds; value 0~999.
Return value:
{Date} Returns a converted Date object.
Example:
The code copy is as follows:
var dt = new Date(2014, 11); // December 2014 (the month number entered here is 11)
console.log(dt); // => {Date}:2014/12/01 00:00:00
dt = new Date(2014, 11, 25); // December 25, 2014
console.log(dt); // => {Date}:2014/12/25 00:00:00
dt = new Date(2014, 11, 25, 15, 30, 40); // December 25, 2014 15:30:40
console.log(dt); // => {Date}:2014/12/25 15:30:40
dt = new Date(2014, 12, 25); // December 25, 2014 (the month number entered here is 12, indicating the 13th month, jump to January of the second year)
console.log(dt); // => {Date}:2015/01/25
3. Properties
None; Date objects can only operate on dates and times through methods.
4. Example method
The instance methods of the Date object are mainly divided into two forms: local time and UTC time. For the same method, there are generally two time format operations (the method name has UTC, which is to operate UTC time). Here we mainly introduce the operations on local time.
4.1 get method
4.1.1 getFullYear(): Returns the year value of the Date object; 4-bit 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 range of values 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 week of the Date object; 0 is Sunday, 1 is Monday, 2 is Tuesday, and so on
4.1.9 getTime(): Returns the millisecond value between the Date object and '1970/01/01 00:00:00' (the time zone of Beijing time is East 8, and the actual starting time is: '1970/01/01 08:00:00').
Example:
The code copy is as follows:
dt.getFullYear(); // => 2014: Year
dt.getMonth(); // => 11: Month; it is actually December (month is calculated from 0)
dt.getDate(); // => 25:Day
dt.getHours(); // => 15:
dt.getMinutes(); // => 30: points
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 '1970/01/01 00:00:00' (the time zone of Beijing time is East 8, and the starting time is actually: '1970/01/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-bit year.
4.2.2 setMonth(month, opt_date): Sets the month value of the Date object. 0 means January, 11 means 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): Set the second value of the Date object.
4.2.7 setMilliseconds(msec): Set the millisecond value of the Date object.
Example:
The code copy is as follows:
var dt = new Date();
dt.setFullYear(2014); // => 2014: Year
dt.setMonth(11); // => 11: Month; it is actually December (month is calculated from 0)
dt.setDate(25); // => 25:Day
dt.setHours(15); // => 15:
dt.setMinutes(30); // => 30: points
dt.setSeconds(40); // => 40: seconds
dt.setMilliseconds(333); // => 333: milliseconds
console.log(dt); // => December 25, 2014 15:30:40 seconds 333 milliseconds
4.3 Other methods
4.3.1 toString(): Convert Date to a 'year, month, day, hour, minute, and second' string
4.3.2 toLocaleString(): Convert Date to a local format string of 'year, month, day, hour, minute, and second'
4.3.3 toDateString(): Convert Date to a 'year, month, day' string
4.3.4 toLocaleDateString(): Convert Date to a local format string of 'year, month and day'
4.3.5 toTimeString(): Convert Date to a 'time, minute and second' string
4.3.6 toLocaleTimeString(): Convert Date to a 'time, minute and second' local format string
4.3.7 valueOf(): Like getTime(), it returns the millisecond value between the Date object and '1970/01/01 00:00:00' (the time zone of Beijing time is East 8, and the starting time is actually: '1970/01/01 08:00:00')
Example:
The code copy 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, and second' string
console.log(dt.toLocaleString()); // => December 23, 2014 at 10:56:11 pm: Convert Date to a local format string of 'year, month, day, hour, minute, and second'
console.log(dt.toDateString()); // => Tue Dec 23 2014: Convert Date to a 'year, month, day' string
console.log(dt.toLocaleDateString()); // => December 23, 2014: Convert Date to a local format string of 'year, month, and date'
console.log(dt.toTimeString()); // => 22:56:11 GMT+0800 (China Standard Time): Convert Date to a 'hour, minute and second' string
console.log(dt.toLocaleTimeString()); // => 10:56:11 pm: Convert Date to a 'hour, minute, and second' local format string
console.log(dt.valueOf()); // => Returns the millisecond value between the Date object and '1970/01/01 00:00:00' (the time zone of Beijing time is East 8, and the starting time is actually: '1970/01/01 08:00:00')
5. Static method
5.1 Date.now()
Description: Return the millisecond value between the Date object of the current date and time and '1970/01/01 00:00:00' (the time zone of Beijing time is East 8, and the actual starting time is: '1970/01/01 08:00:00')
Parameters: None
Return value:
{int}: The number of milliseconds between the current time and the start time.
Example:
The code copy is as follows:
console.log(Date.now()); // => 1419431519276
5.2 Date.parse(dateStr)
Description: Convert the string to a Date object, and then return the millisecond value between this Date object and '1970/01/01 00:00:00' (the time zone of Beijing time is East 8, and the starting time is actually: '1970/01/01 08:00:00')
parameter:
①dateStr {string}: A string that can be converted into a Date object (time can be omitted); there are two main formats of strings:
1) yyyy/MM/dd HH:mm:ss (recommended): If time is omitted, the time of the returned Date object is 00:00:00.
2) yyyy-MM-dd HH:mm:ss: If time is omitted, the time of the returned Date object is 08:00:00 (plus the local time zone). If time is not omitted, this string returns NaN (non-number) in IE!
Return value:
{int} Returns the number of milliseconds between the converted Date object and the start time.
Example:
The code copy is as follows:
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 method returns NaN in IE!)
6. Practical operation
6.1 Convert the DateTime type of C# to the Date object of Js
Note: The format returned to the foreground through Json serialization is "//Date(1419492640000)//". The number in the middle represents the number of milliseconds between the value of DateTime and the start time.
Example:
Background code: simple ashx
The code copy is as follows:
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); // Serialize to Json
context.Response.ContentType = "text/plain";
context.Response.Write(rs);
}
Front Desk Code:
The code copy is as follows:
var dateTimeJsonStr = '//Date(1419492640000)//'; // C# Json format for DateTime type conversion
var msecStr = dateTimeJsonStr.toString().replace(///Date/(([-]?/d+)/)///gi, "$1"); // => '1419492640000' : Get the millisecond string by regular replacement
var msesInt = Number.parseInt(msecStr); // Convert millisecond string to numeric value
var dt = new Date(msesInt); // Initialize the Date object
console.log(dt.toLocaleString()); // => December 25, 2014 at 3:30:40 pm
6.2 Get the countdown
Description: Calculate how many days and time difference is between the current time and the target time.
Example:
The code copy is as follows:
/**
* Return to countdown
* @param dt {Date}: Destination Date object
* @return {Strin} : Return countdown: X days X hours X minutes
*/
function getDownTime(dt) {
// 1. Get the countdown
var intervalMsec = dt - Date.now(); // Subtract the current time to get the number of milliseconds of the 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 * 24 * 3600) / 3600); // Hours
var min = parseInt((intervalSec - day * 24 * 3600 - hour * 3600) / 60); // Minutes
// 2. If the milliseconds of the difference are less than 0, it means that the destination time is less than the current time. The values taken at this time are all negative: -X days-hour-minute. When displayed, just display the negative one before the number of days.
if (intervalMsec < 0) {
hour = 0 - hour;
min = 0 - min;
}
// 3. Splice the string and return
var rs = day + 'day' + hour + 'hour' + min + 'minute';
return rs;
}
// Current time: 2014/12/28 13:26
console.log(getDownTime(new Date('2015/06/01'))); // => 154 days 10:33
console.log(getDownTime(new Date('2014/01/01'))); // => -361 days 13:26
6.3 Comparison of the size of 2 Date objects
Note: You can compare the milliseconds of the two and the starting time to distinguish the size.
Example:
The code copy is as follows:
var dt1 = new Date('2015/12/01');
var dt2 = new Date('2015/12/25');
console.log(dt1 > dt2); // => false