search
HomeWeb Front-endJS TutorialJavascript date object Date extension method_time and date

Today I excerpted some related methods of operating dates in js from the Internet, and now I will share them with you.

Copy code The code is as follows:

> ;


The specific extension methods are as follows:
parseCHS - static method. Parse commonly used Chinese dates and return date objects.
add - date addition and subtraction operations. [Note: There is a BUG in this function when uploading. Please download and change the first line "var regExp = /^d $/;" in this function to "var regExp = /^([ -])?d $/;", otherwise the subtraction will not be possible. ]
dateDiff - date difference. The difference between the start date and the current date, returns the absolute value of the difference.
getFirstWeekDays——Get the number of days in the first week of the year where the current date is located.
getLastWeekDays——Get the number of days in the last week of the year where the current date is located.
getWeeksOfYear——Get the number of weeks in the year of the current date.
getWeek - Get the week of the year where the current date is. Returns an integer value.
getSeason——Get the season of the year where the current date is. Returns a quarter integer value.
For detailed comments and parameters, please refer to the comments in the JS file.
Copy code The code is as follows:

/*
========================================== ==============================================
Description :Date object extension. Including commonly used Chinese date format analysis, addition and subtraction operations, date difference, weekly operations and quarterly operations.
Author:Dezwen.
Date:2009-5-30.
============================== ================================================== ======
*/
Date.parseCHS = function(dateString) {
///
///Parse commonly used Chinese dates and return date objects.
///

///
//Date string. The formats included are: "xxxx(xx)-xx-xx xx:xx:xx", "xxxx(xx).xx.xx xx:xx:xx",
///"xxxx(xx)年xx" Month xx day xx hour xx minute xx second"
///
var regExp1 = /^d{4}-d{1,2}-d{1,2}( d{ 1,2}:d{1,2}:d{1,2})?$/;
var regExp2 = /^d{4}.d{1,2}.d{1,2}( d{1,2}:d{1,2}:d{1,2})?$/;
var regExp3 = /^d{4} year d{1,2} month d{1,2 }Day (d{1,2} hour d{1,2} minute d{1,2} second)?$/;
if (regExp1.test(dateString)) { }
else if (regExp2 .test(dateString)) {
dateString = dateString.replace(/./g, "-");
}
else if (regExp3.test(dateString)) {
dateString = dateString .replace("year", "-").replace(
"month", "-").replace("day", "").replace("hour", ":").replace(" Minutes", ":"
).replace("seconds", "");
}
else {
throw "The format of the parameter value passed to Date.parseCHS is incorrect. Please pass it. A valid date format string as parameter ";
}
var date_time = dateString.split(" ");
var date_part = date_time[0].split("-");
var time_part = (date_time.length > 1 ? date_time[1].split(":") : "");
if (time_part == "") {
return new Date(date_part[0 ], date_part[1] - 1, date_part[2]);
}
else {
return new Date(date_part[0], date_part[1] - 1, date_part[2], time_part[ 0], time_part[1], time_part[2]);
}
}
Date.prototype.add = function(datepart, number, returnNewObjec) {
///
///Date addition and subtraction.
///If the returnNewObjec parameter is true, the operation result is returned by a new date object, and the original date object remains unchanged.
///Otherwise, the original date object is returned. At this time, the original date object is The value is the result of the operation.
///

///
///The plus and minus parts of the date:
///Year, yy, yyyy--year
///quarter, qq, q--quarter
///Month, mm, m -- month
///dayofyear, dy , y-- day
///Day, dd, d -- day
///Week, wk, ww -- week
///Hour, hh -- hour
// /minute, mi, n -- minutes
///second, ss, s -- seconds
///millisecond, ms -- milliseconds
///
/ //
///Amount to be added or subtracted
///
///
///Whether to return a new date object. If the parameter is true, a new date object is returned, otherwise the current date object is returned.
///
///
///Return a date object
///

var regExp = /^d $/;
if (regExp.test(number)) {
number = parseInt(number);
}
else { number = 0; }
datepart = datepart.toLowerCase();
var tDate;
if (typeof (returnNewObjec) == "boolean" ) {
if (returnNewObjec == true) {
tDate = new Date(this);
}
else { tDate = this; }
}
else { tDate = this ; }

switch (datepart) {
case "year":
case "yy":
case "yyyy":
tDate.setFullYear(this.getFullYear() number );
break;
case "quarter":
case "qq":
case "q":
tDate.setMonth(this.getMonth() (number * 3));
break;
case "month":
case "mm":
case "m":
tDate.setMonth(this.getMonth() number);
break;
case "dayofyear":
case "dy":
case "y":
case "day":
case "dd":
case "d":
tDate.setDate(this.getDate() number);
break;
case "week":
case "wk":
case "ww":
tDate.setDate(this. getDate() (number * 7));
break;
case "hour":
case "hh":
tDate.setHours(this.getHours() number);
break
case "minute":
case "mi":
case "n":
tDate.setMinutes(this.getMinutes() number);
break
case "second" :
case "ss":
case "s":
tDate.setSeconds(this.getSeconds() number);
break;
case "millisecond":
case " ms":
tDate.setMilliseconds(this.getMilliseconds() number);
break;
}
return tDate;
}
Date.prototype.dateDiff = function(datepart, beginDate) {
///
///The difference between the start date and the current date, returns the absolute value of the difference.
///

///
///Additional and subtractive parts of the date:
/// Year, yy, yyyy--year;
///quarter, qq, q --quarter
///Month, mm, m -- month
///dayofyear, dy, y-- Day
///Day, dd, d -- day
///Week, wk, ww -- week
///Hour, hh -- hour
///minute, mi , n -- minutes
///second, ss, s -- seconds
///millisecond, ms -- milliseconds
///
///
///To compare my dates
///
///
///Returns the absolute value of the date difference.
///

datepart = datepart.toLowerCase();
var yearDiff = Math.abs(this.getFullYear() - beginDate.getFullYear());
switch ( datepart) {
case "year":
case "yy":
case "yyyy":
return yearDiff;
case "quarter":
case "qq":
case "q":
var qDiff = 0;
switch (yearDiff) {
case 0:
qDiff = Math.abs(this.getSeason() - beginDate.getSeason()) ;
break;
case 1:
qDiff = (this.getSeason() - new Date(this.getFullYear(), 0, 1).getSeason())
(new Date(beginDate .getFullYear(), 11, 31).getSeason() -
beginDate.getSeason()) 1;
break;
default:
qDiff = (this.getSeason() - new Date( this.getFullYear(), 0, 1).getSeason())
(new Date(beginDate.getFullYear(), 11, 31).getSeason() -
beginDate.getSeason()) 1 (yearDiff - 1) * 4;
break;
}
return qDiff;
case "month":
case "mm":
case "m":
var monthDiff = 0;
switch (yearDiff) {
case 0:
monthDiff = Math.abs(this.getMonth() - beginDate.getMonth());
break;
case 1:
monthDiff = (this.getMonth() - new Date(this.getFullYear(), 0, 1).getMonth())
(new Date(beginDate.getFullYear(), 11, 31).getMonth() -
beginDate.getMonth()) 1;
break;
default:
monthDiff = (this.getMonth() - new Date(this.getFullYear(), 0, 1).getMonth( ))
(new Date(beginDate.getFullYear(), 11, 31).getMonth() -
beginDate.getMonth()) 1 (yearDiff - 1) * 12;
break;
}
return monthDiff;
case "dayofyear":
case "dy":
case "y":
case "day":
case "dd":
case "d":
return Math.abs((this.setHours(0, 0, 0, 0) - beginDate.setHours(0, 0, 0, 0)) / 1000 / 60 / 60 / 24);
case "week":
case "wk":
case "ww":
var weekDiff = 0;
switch (yearDiff) {
case 0:
weekDiff = Math.abs(this.getWeek() - beginDate.getWeek());
break;
case 1:
weekDiff = (this.getWeek() - new Date(this.getFullYear(), 0, 1).getWeek())
(new Date(beginDate.getFullYear(), 11, 31).getWeek() -
beginDate.getWeek()) 1;
break;
default:

weekDiff = (this.getWeek() - new Date(this.getFullYear(), 0, 1).getWeek())
(new Date(beginDate.getFullYear(), 11, 31).getWeek() -
beginDate.getWeek()) 1;
var thisYear = this.getFullYear();
for (var i = 1; i weekDiff = new Date(thisYear - i, 0, 1).getWeeksOfYear();
}
break;
}
return weekDiff;
case "hour":
case "hh":
return Math.abs((this - beginDate) / 1000 / 60 / 60);
case "minute":
case "mi":
case "n":
return Math.abs((this - beginDate) / 1000 / 60);
case "second":
case "ss":
case "s":
return Math.abs( (this - beginDate) / 1000);
case "millisecond":
case "ms":
return Math.abs(this - beginDate);
}
}
Date .prototype.getFirstWeekDays = function() {
///
///Get the number of days in the first week of the year where the current date is located
///

return (7 - new Date(this.getFullYear(), 0, 1).getDay()); //The month in JS also starts from 0, 0 means January, and so on.
}
Date.prototype.getLastWeekDays = function(year) {
///
///Get the number of days in the last week in the year where the current date is located
// /

return (new Date(this.getFullYear(), 11, 31).getDay() 1); //The month in JS also starts from 0, 0 means January, so on analogy.
}
Date.prototype.getWeeksOfYear = function() {
///
///Get the week number of the year in which the current date is located
/// summary>
return (Math.ceil((new Date(this.getFullYear(), 11, 31, 23, 59, 59) -
new Date(this.getFullYear(), 0, 1)) / 1000 / 60 / 60 / 24) -
this.getFirstWeekDays() - this.getLastWeekDays()) / 7 2;
}
Date.prototype.getSeason = function() {
// /
///Get the quarter of the year where the current date is. Returns a quarter integer value.
///

var month = this.getMonth();
switch (month) {
case 0:
case 1:
case 2:
return 1;
case 3:
case 4:
case 5:
return 2;
case 6:
case 7:
case 8:
return 3;
default:
return 4;
}
}
Date.prototype.getWeek = function() {
///
///获取当前日期所在是一年中的第几周。返回一个整数值。
///

var firstDate = new Date(this.getFullYear(), 0, 1);
var firstWeekDays = this.getFirstWeekDays();
var secondWeekFirstDate = firstDate.add("dd", firstWeekDays, true);
var lastDate = new Date(this.getFullYear(), 11, 31);
var lastWeekDays = this.getLastWeekDays();
if (this.dateDiff("day", firstDate) return 1;
}
else if (this.dateDiff("day", lastDate) return this.getWeeksOfYear();
}
else {
return Math.ceil((this - secondWeekFirstDate) / 1000 / 60 / 60 / 24 / 7) 1;
}
}
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 C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function