Javascript 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.
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.
/*
========================================== ==============================================
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
///
///< param name="beginDate" type="DateTime">
///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 < yearDiff; 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) < firstWeekDays) {
return 1;
}
else if (this.dateDiff("day", lastDate) < lastWeekDays) {
return this.getWeeksOfYear();
}
else {
return Math.ceil((this - secondWeekFirstDate) / 1000 / 60 / 60 / 24 / 7) 1;
}
}

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service
