search
HomeWeb Front-endJS TutorialDetailed explanation of JavaScript Date object_javascript skills

This article mainly introduces the operation of Date date and time objects. The specific content is as follows

Table of Contents
1. Introduction: Explain the Date object.

2. Constructor: Introduce several methods of constructor new Date() of Date object.

3. Instance methods: Introducing the get, set and other instance methods of the Date object.

4. Static methods: Introducing the static methods of Date object: Date.now(), Date.parse(), etc.

5. Practical operations: Introducing some examples of Date objects: getting countdown, comparing the size of two Date objects, etc.

1. Introduction
1.1 Description

Date object is an object for operating date and time. The Date object can only operate on date and time through methods.

1.2 Properties

None; Date objects can only operate on date and time 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:

var dt = new Date();
console.log(dt); // => 返回一个表示本地日期和时间的Date对象

2.2 new Date(milliseconds): Convert milliseconds to Date object

Parameters:

①milliseconds {int}: The number of milliseconds; indicating the number of milliseconds starting from '1970/01/01 00:00:00' as the starting point.

Note: The current time zone must be added to the starting point. The time zone of Beijing time is East 8th District. The actual starting time is: '1970/01/01 08:00:00'

Return value:

{Date} returns a superimposed Date object.

Example:

var dt = new Date(1000 * 60 * 1); // 前进1分钟的毫秒数
console.log(dt); // => {Date}:1970/01/01 08:01:00
dt = new Date(-1000 * 60 * 1); // 倒退1分钟的毫秒数
console.log(dt); // => {Date}:1970/01/01 07:59:00

2.3 new Date(dateStr): Convert string to Date object

Parameters:

①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 the time is omitted, the time of the returned Date object is 00:00:00.

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

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
console.log(dt); // => {Date}:2014-12-25 08:00:00 (加上了东8区的时区)
dt = new Date('2014-12-25 12:00:00'); // yyyy-MM-dd HH:mm:ss (注意:此转换方式在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, hours, minutes and seconds into Date objects

Parameters:

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

②month {int}: month; 2 digits. Calculation starts from 0, 0 represents January and 11 represents December.

③opt_day {int} Optional: number; 2 digits; counting from 1, 1 means No. 1.

④opt_hours {int} Optional: hours; 2 digits; value 0~23.

⑤opt_minutes {int} Optional: minutes; 2 digits; value 0~59.

⑥opt_seconds {int} Optional: seconds; 2 unnumbered; value 0~59.

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

Return value:

{Date} returns a converted Date object.

Example:

var dt = new Date(2014, 11); // 2014年12月(这里输入的月份数字为11)
console.log(dt); // => {Date}:2014/12/01 00:00:00
dt = new Date(2014, 11, 25); // 2014年12月25日
console.log(dt); // => {Date}:2014/12/25 00:00:00
dt = new Date(2014, 11, 25, 15, 30, 40); // 2014年12月25日 15点30分40秒
console.log(dt); // => {Date}:2014/12/25 15:30:40
dt = new Date(2014, 12, 25); // 2014年13月25日(这里输入的月份数字为12,表示第13个月,跳转到第二年的1月)
console.log(dt); // => {Date}:2015/01/25

3. Instance methods
The instance methods of Date objects are mainly divided into two forms: local time and UTC time. The same method generally operates on these two time formats (the method name with UTC is the operation of UTC time). Here we mainly introduce the operation of local time.

3.1 get method

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

3.1.2 getMonth(): Returns the month value of the Date object. Starts from 0, so real month = return value + 1.

3.1.3 getDate(): Returns the date value in the month of the Date object; the value range is 1~31.

3.1.4 getHours(): Returns the hour value of the Date object.

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

3.1.6 getSeconds(): Returns the seconds value of the Date object.

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

3.1.8 getDay(): Returns the day of the week value of the Date object; 0 is Sunday, 1 is Monday, 2 is 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 of Beijing time is East 8th District, the starting time is actually: '1970/01 /01 08:00:00').

Example:

dt.getFullYear(); // => 2014:年
dt.getMonth(); // => 11:月;实际为12月份(月份从0开始计算)
dt.getDate(); // => 25:日
dt.getHours(); // => 15:时
dt.getMinutes(); // => 30:分
dt.getSeconds(); // => 40:秒
dt.getMilliseconds(); // => 333:毫秒
dt.getDay(); // => 4:星期几的值
dt.getTime(); // => 1419492640333 :返回Date对象与'1970/01/01 00:00:00'之间的毫秒值(北京时间的时区为东8区,起点时间实际为:'1970/01/01 08:00:00')

3.2 set method

3.2.1 setFullYear(year, opt_month, opt_date): Set the year value of the Date object; 4-digit year.

3.2.2 setMonth(month, opt_date): Set the month value of the Date object. 0 represents January and 11 represents December.

3.2.3 setDate(date): Set the date value in the month of the Date object; the value range is 1~31.

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

3.2.5 setMinutes(min, opt_sec, opt_msec): Set the minute value of the Date object.

3.2.6 setSeconds(sec, opt_msec): Set the seconds value of the Date object.

3.2.7 setMilliseconds(msec): Set the millisecond value of the Date object.

Example:

var dt = new Date();
dt.setFullYear(2014); // => 2014:年
dt.setMonth(11); // => 11:月;实际为12月份(月份从0开始计算)
dt.setDate(25); // => 25:日
dt.setHours(15); // => 15:时
dt.setMinutes(30); // => 30:分
dt.setSeconds(40); // => 40:秒
dt.setMilliseconds(333); // => 333:毫秒
console.log(dt); // => 2014年12月25日 15点30分40秒 333毫秒

3.3 其他方法

3.3.1 toString() :将Date转换为一个'年月日 时分秒'字符串

3.3.2 toLocaleString() :将Date转换为一个'年月日 时分秒'的本地格式字符串

3.3.3 toDateString() :将Date转换为一个'年月日'字符串

3.3.4 toLocaleDateString() :将Date转换为一个'年月日'的本地格式字符串

3.3.5 toTimeString() :将Date转换为一个'时分秒'字符串

3.3.6 toLocaleTimeString() :将Date转换为一个'时分秒'的本地格式字符串

3.3.7 valueOf() :与getTime()一样, 返回Date对象与'1970/01/01 00:00:00'之间的毫秒值(北京时间的时区为东8区,起点时间实际为:'1970/01/01 08:00:00')

示例:

var dt = new Date();
console.log(dt.toString()); // => Tue Dec 23 2014 22:56:11 GMT+0800 (中国标准时间) :将Date转换为一个'年月日 时分秒'字符串
console.log(dt.toLocaleString()); // => 2014年12月23日 下午10:56:11 :将Date转换为一个'年月日 时分秒'的本地格式字符串
 
console.log(dt.toDateString()); // => Tue Dec 23 2014 :将Date转换为一个'年月日'字符串
console.log(dt.toLocaleDateString()); // => 2014年12月23日 :将Date转换为一个'年月日'的本地格式字符串
 
console.log(dt.toTimeString()); // => 22:56:11 GMT+0800 (中国标准时间) :将Date转换为一个'时分秒'字符串
console.log(dt.toLocaleTimeString()); // => 下午10:56:11 :将Date转换为一个'时分秒'的本地格式字符串
 
console.log(dt.valueOf()); // => 返回Date对象与'1970/01/01 00:00:00'之间的毫秒值(北京时间的时区为东8区,起点时间实际为:'1970/01/01 08:00:00')

四. 静态方法
4.1 Date.now()

说明:返回当前日期和时间的Date对象与'1970/01/01 00:00:00'之间的毫秒值(北京时间的时区为东8区,起点时间实际为:'1970/01/01 08:00:00')

参数:无

返回值:

{int} :当前时间与起始时间之间的毫秒数。

示例:

console.log(Date.now()); // => 1419431519276

4.2 Date.parse(dateStr)

说明:把字符串转换为Date对象 ,然后返回此Date对象与'1970/01/01 00:00:00'之间的毫秒值(北京时间的时区为东8区,起点时间实际为:'1970/01/01 08:00:00')

参数:

①dateStr {string} :可转换为Date对象的字符串(可省略时间);字符串的格式主要有两种:

1) yyyy/MM/dd HH:mm:ss (推荐):若省略时间,返回的Date对象的时间为 00:00:00。

2) yyyy-MM-dd HH:mm:ss :若省略时间,返回的Date对象的时间为 08:00:00(加上本地时区)。若不省略时间,此字符串在IE中返回NaN(非数字)!

返回值:

{int} 返回转换后的Date对象与起始时间之间的毫秒数。

示例:

console.log(Date.parse('2014/12/25 12:00:00')); // => 1419480000000
console.log(Date.parse('2014-12-25 12:00:00')); // => 1419480000000 (注意:此转换方式在IE中返回NaN!)

五. 实际操作
5.1 C#的DateTime类型转换为Js的Date对象

说明:C#的DateTime类型通过Json序列化返回给前台的格式为:"\/Date(1419492640000)\/" 。中间的数字,表示DateTime的值与起始时间之间的毫秒数。

示例:

后台代码:简单的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); // 序列化成Json
 context.Response.ContentType = "text/plain";
 context.Response.Write(rs);
}

前台代码:

var dateTimeJsonStr = '\/Date(1419492640000)\/'; // C# DateTime类型转换的Json格式
var msecStr = dateTimeJsonStr.toString().replace(/\/Date\(([-]?\d+)\)\//gi, "$1"); // => '1419492640000' :通过正则替换,获取毫秒字符串
var msesInt = Number.parseInt(msecStr); // 毫秒字符串转换成数值
var dt = new Date(msesInt); // 初始化Date对象
console.log(dt.toLocaleString()); // => 2014年12月25日 下午3:30:40

5.2  获取倒计时

说明:计算当前时间离目的时间相差多少天时分。

示例:

/**
* 返回倒计时
* @param dt {Date}:目的Date对象
* @return {Strin} :返回倒计时:X天X时X分
*/
function getDownTime(dt) {
 // 1.获取倒计时
 var intervalMsec = dt - Date.now(); // 目的时间减去现在的时间,获取两者相差的毫秒数
 var intervalSec = intervalMsec / 1000; // 转换成秒数
 var day = parseInt(intervalSec / 3600 / 24); // 天数
 var hour = parseInt((intervalSec - day * 24 * 3600) / 3600); // 小时
 var min = parseInt((intervalSec - day * 24 * 3600 - hour * 3600) / 60); // 分钟
 
 // 2.若相差的毫秒小于0 ,表示目的时间小于当前时间,这时的取的值都是负的:-X天-时-分,显示时,只显示天数前面为负的就行。
 if (intervalMsec < 0) {
  hour = 0 - hour;
  min = 0 - min;
 }
 
 // 3.拼接字符串并返回
 var rs = day + '天' + hour + '时' + min + '分';
 return rs;
}
 
// 当前时间:2014/12/28 13:26
console.log(getDownTime(new Date('2015/06/01'))); // => 154天10时33分
console.log(getDownTime(new Date('2014/01/01'))); // => -361天13时26分
 

5.3 比较2个Date对象的大小

说明:可以对比2者的与起始时间的毫秒数,来区分大小。

示例:

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

以上就是本文的全部内容,希望对大家的学习有所帮助。

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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools