Home  >  Article  >  Web Front-end  >  How to operate date object in JS

How to operate date object in JS

php中世界最好的语言
php中世界最好的语言Original
2017-12-02 10:30:421495browse

Date is similar to Array in js. They are both special objects with their own special methods.

Because I don’t use Date much, my understanding of it is quite shallow. Last week, I was asked how to get the number of days in a certain month of a certain year. I thought about it for a while and answered that there are two types. One is to write the logic of leap year judgment by myself. The number of days in each month is stored in an array in two situations. It uses the characteristics of js Date object (actually he summarized it...). But I can't tell you exactly what features are used. Now that I think about it, let’s learn and summarize it.

Date get and set series

(Note: The specific reference time of getTime() is 8:00:00 on January 1, 1970)

All sets There are corresponding get series.

It is worth noting that all get and set must initialize an instance and call it as the attribute of the instance. Such as:

It is actually very easy to understand. After all, if you want to set or return the value of a Date object, it must be worth existing first. The standard way of writing is var date=new Date(2015,7,30);date.getDate()

If no parameters are passed in new Date(), and no set series method is used, then Refers to the current value (local computing clock), including hours, minutes and seconds. This feature can be easily used in js to display the current time in any form.

var date = new Date(),
    nowYear = date.getFullYear(),
    nowMonth = date.getMonth() + 1,  //注意getMonth从0开始,getDay()也是(此时0代表星期日)
    nowDay = date.getDate(),
    nowHour = date.getHours(),
    nowMinute = date.getMinutes(),
    nowSecond = date.getSeconds(),
    weekday = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
    nowWeek = weekday[date.getDay()];
console.log(nowYear + '年' + nowMonth + '月' + nowDay + '日' + nowHour + '时' + nowMinute + '分' + nowSecond + '秒' + nowWeek);

Similarly, you can easily create clock effects by using the built-in setInterval or setTimeout callback methods.

The first is valueOf() (get the real value) and toString() (get the value in string form) that each object has. Note the difference within the red box.

toTimeString(): Convert the time part of the Date object into a string and return it, so there must be a time parameter and an instance,

toDateString(): Convert the date part of the Date object into String and returned, must have an instance.

Parse(): Returns the number of milliseconds from 8:00 on January 1, 1970 to the specified date (string), accurate to seconds. It can only be called in the form of Date.parse (Date instance). (Pay attention to compare getTime(), accurate to milliseconds.)

 toSource(): Return to the source code.

Note: toLocaleString: Converts the Date object into a string according to the local time format, corresponding to UTC and GMT. This method is obsolete in both Array and Date, so there is no need to worry about it anymore. The UTC series is rarely used, that is, the format is different.

Summary of important knowledge points

Discussion of parameters of the set series

The first three parameters of setFullYear() are useful. Hours, minutes and seconds are still local~~~

In other set series, only the first parameter is useful, and the return values ​​are based on new Date() (current time) plus Month/Date/Minutes * corresponding to the first parameter.

Set the complete time

Obviously setTime is also a set series, so it only adds 1992 milliseconds (displayed as 1s) to the original basis. Since setTime is quite special, it was tested at 8 a.m. on January 1, 1970 (FF, Chrome, IE5+, Opera (safari is not used enough so I didn’t test it)). Although w3School said it was 0 o’clock, test the new Date ( 1970,0,1,8,0,0).getTime() is obviously displayed as 0), so before actual execution, the date instance is no longer the current time corresponding to new Date() , but there is a process of being converted into a base time. So the displayed value is 1970,0,1,8,0,1. If 1992 is changed to 5000, it will be 1970,0,1,8,0,5.

As for the method of setting the complete time, pass in the parameters of the time that need to be set when using the new Date object. It can be the digital form of 1992, 10, 3, 10, 2, 50 (you can also add milliseconds and then use getTime() to detect it, but it is generally not used) (representing 10:02 on November 3, 1992 50 seconds), or it can be in standard string format (but it is generally not written like this~~~).

    getDate()

Usually placed at the back for the finale, hehe.

As a get series, in addition to the number of parameters, the value of the parameters is also very particular. First answer the original question and get the maximum number of days in a certain month of a certain year (which can be understood as judging a leap year~).

new Date(2014,2,0).getDate();     //返回2014年2月份的最后一天(28)

When the third parameter is 0, it actually returns the last day of the previous month (note that the number 2 of the month is actually March, so the code returns the last day of February in the current month serial number). See more examples

Copy code

new Date(2014,1,30).getDate();     //返回2014年3月2日在3月份中的天数(2)
new Date(2014,2,-1).getDate();     //返回2014年2月份的倒数第二天(27)

//When the parameters are missing, 1 is displayed

new Date(2014,8).getDate(); 
new Date(14,18).getDate(); 
new Date(180).getDate();

//When the parameters are redundant, the redundant ones have no effect. (The operation of arguments[3+] is not set)

new Date(2015,2,0,2).getDate();

Copy code

If there are too many days, it will be automatically calculated to the next month. If the number of days is negative, it will be calculated to the previous month. If there are too few parameters, there will be a problem. If there are too many parameters, the extra parts will have no effect. Compared with other set series, it is almost the same implementation idea. You will know it by looking at (2).

Time objects in the form of new Date('xxxx/xx/xx xx:xx:xx') can be correctly recognized on both IOS and Andriod systems, and time objects in the form of new Date('xxxx-xx- Time objects in the form of xx xx:xx:xx') cannot be correctly recognized on the iOS system and require a layer of conversion.

function parseDate(dateStr) {
  if (!dateStr) {
    return new Date();
  }
 
  if (dateStr.indexOf('/') > -1) {
    return new Date(dateStr);
  } else {
    return new Date(dateStr.replace(/-/g, '/'));
  }
}

I believe you have mastered the methods after reading these cases. For more exciting information, please pay attention to other related articles on the php Chinese website!

Related Reading:

How to set the text font color in CSS

How to set the font color in CSS

In CSS Differences in types of box models

The above is the detailed content of How to operate date object in JS. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn