search
HomeWeb Front-endJS TutorialHow to operate date object in JS

How to operate date object in JS

Dec 02, 2017 am 10:30 AM
datejavascriptoperate

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
JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.