Key Takeaways
- jQuery DATETIME functions are incredibly versatile, offering a complete range of date and time manipulations, including getting the date, converting dates, validating dates, and comparing dates.
- The functions also include capabilities to convert date strings to date objects, determine if a departure and return date are valid, and detect if a year is a leap year.
- The JQUERY4U.DATETIME.js library also includes a comprehensive date formatting function, similar to PHP’s date function, allowing for custom date formats.
- The library is easy to implement, with a minimal overhead ensuring speed and accuracy, making it a preferred choice over other date/time libraries.
jQuery Date/Time Complete Listing
<span>/*___ FILE: "JQUERY4U.datetime.js" ___*/ </span><span>;(function($) </span><span>{ </span> <span>/** </span><span> * jQuery Date and time functions - Complete List </span><span> */ </span> <span>var JQUERY4U = JQUERY4U || {}; </span> <span>JQUERY4U.DATETIME = </span> <span>{ </span> <span>/** </span><span> * Name of this class (used for error handling and/or debugging purposes) </span><span> * <span>@type String </span></span><span> */ </span> <span>name: 'JQUERY4U.DATETIME', </span> <span>init: function() </span> <span>{ </span> <span>JQUERY4U.UTIL.handleErrors(this); </span> <span>Date.prototype.<span>JQUERY4UFormat</span> = this.format; </span> <span>}, </span> <span>/** </span><span> * Return today's date in dd/mm/yyyy format </span><span> * <span>@returns <span>{String}</span> Date in dd/mm/yyyy format </span></span><span> */ </span> <span>todaysDate: function() </span> <span>{ </span> <span>return this.futureDateDays(0); </span> <span>}, </span> <span>/** </span><span> * Return tomorrow's date in dd/mm/yyyy format </span><span> * <span>@returns <span>{String}</span> Date in dd/mm/yyyy format </span></span><span> */ </span> <span>tomorrowsDate: function() </span> <span>{ </span> <span>return this.futureDateDays(1); </span> <span>}, </span> <span>/** </span><span> * Return date 7 days from now in dd/mm/yyyy format </span><span> * <span>@returns <span>{String}</span> Date in dd/mm/yyyy format </span></span><span> */ </span> <span>weekFromToday: function() </span> <span>{ </span> <span>return this.futureDateDays(7); </span> <span>}, </span> <span>/** </span><span> * Return the first day of the next month </span><span> * <span>@returns <span>{String}</span> Date in dd/mm/yyyy format </span></span><span> */ </span> <span>firstDayNextMonth: function() </span> <span>{ </span> <span>var today = new Date(); </span> nextMonth <span>= new Date(today.getFullYear(), today.getMonth() + 1, 1); </span> nextMonth<span>.getDate() +'/'+ (nextMonth.getMonth() + 1) +'/'+ nextMonth.getFullYear(); </span> <span>return this.leadingZero(nextMonth.getDate()) +'/'+ this.leadingZero(nextMonth.getMonth() + 1) +'/'+ nextMonth.getFullYear(); </span> <span>}, </span> <span>/** </span><span> * Returns x number of dates date in the future in dd/mm/yyyy format </span><span> * <span>@param <span>{Integer}</span> days Number of days into the future </span></span><span> * <span>@returns <span>{String}</span> Date in dd/mm/yyyy format </span></span><span> */ </span> <span>futureDateDays: function(days) </span> <span>{ </span> <span>var futureDate = new Date(); </span> futureDate<span>.setDate(futureDate.getDate() + days); </span> <span>return this.leadingZero(futureDate.getDate()) +'/'+ this.leadingZero(futureDate.getMonth() + 1) +'/'+ this.leadingZero(futureDate .getFullYear()); </span> <span>}, </span> <span>/** </span><span> * Return the current time in HHMM format </span><span> * <span>@returns <span>{String}</span> Time in HHMM (e.g. 23:12) format </span></span><span> */ </span> <span>timeHHMM: function() </span> <span>{ </span> <span>var today = new Date(); </span> <span>return this.leadingZero(today.getHours()) + this.leadingZero(today.getMinutes()); </span> <span>}, </span> <span>/** </span><span> * Return the current time in HHMMSS format </span><span> * <span>@returns <span>{String}</span> Time in HHMMSS (e.g. 23:12:33) format </span></span><span> */ </span> <span>timeHHMMSS: function() </span> <span>{ </span> <span>var today = new Date(); </span> <span>return this.leadingZero(today.getHours()) +':'+ this.leadingZero(today.getMinutes()) +':'+ this.leadingZero(today.getSeconds()); </span> <span>}, </span> <span>/** </span><span> * Takes a date string in Australian format and returns date string in US format </span><span> * <span>@param <span>{String}</span> dateStr Date in dd/mm/yyyy format </span></span><span> * <span>@param <span>{String}</span> <span>[separator=<span>"-"</span>]</span> separator character in return date string </span></span><span> * <span>@returns <span>{String}</span> date in mm/dd/yyyy format </span></span><span> */ </span> <span>convertUSFormat: function(dateStr<span>, separator</span>) </span> <span>{ </span> <span>var separator = (typeof(separator) == 'undefined') ? '-' : separator; </span> <span>var re = new RegExp('([0-9]{2})/([0-9]{2})/([0-9]{4})', 'm'); </span> <span>var matches = re.exec(dateStr); </span> <span>return matches[2] + separator + matches[1] + separator + matches[3]; </span> <span>}, </span> <span>/** </span><span> * Convert date in mm/dd/yyyy format and return in dd-mm-yyyy format (depending upon separator) </span><span> * <span>@param <span>{String}</span> dateStr Date in mm/dd/yyyy format </span></span><span> * <span>@param <span>{String}</span> <span>[separator=<span>"-"</span>]</span> Separator character in return date string </span></span><span> * <span>@returns <span>{String}</span> Date in mm-dd-yyyy format (presuming "-" is separator character) </span></span><span> */ </span> <span>convertUStoAUSDate: function(dateStr<span>, separator</span>) </span> <span>{ </span> <span>var separator = (typeof(separator) == 'undefined') ? '-' : separator; </span> <span>var re = new RegExp('([0-9]{2})/([0-9]{2})/([0-9]{4})', 'm'); </span> <span>var matches = re.exec(dateStr); </span> <span>return matches[2] + separator + matches[1] + separator + matches[3]; </span> <span>}, </span> <span>/** </span><span> * Return whether the supplied date components form the expected date </span><span> * <span>@param <span>{String}</span> year </span></span><span> * <span>@param <span>{String}</span> month </span></span><span> * <span>@param <span>{String}</span> day </span></span><span> * <span>@returns <span>{Boolean}</span> True if the date components match the date values in Date object </span></span><span> */ </span> <span>isValidDate: function(year<span>, month, day</span>) </span> <span>{ </span> <span>var dt = new Date(parseInt(year, 10), parseInt(month, 10)-1, parseInt(day, 10)); </span> <span>if(dt.getDate() != parseInt(day, 10) || dt.getMonth() != (parseInt(month, 10)-1) || dt.getFullYear() != parseInt(year, 10)) </span> <span>{ </span> <span>return false; </span> <span>} </span> <span>return true; </span> <span>}, </span> <span>/** </span><span> * Takes a date object and returns in yyyymmdd format </span><span> * <span>@param <span>{Date Object}</span> dateObj </span></span><span> * <span>@returns <span>{String}</span> Date in yyyymmdd format </span></span><span> */ </span> <span>dateToYYYYMMDD: function(dateObj) </span> <span>{ </span> <span>return (dateObj.getFullYear() + this.leadingZero(dateObj.getMonth() + 1) + this.leadingZero(dateObj.getDate())).toString(); </span> <span>}, </span> <span>/** </span><span> * Takes a date object and returns in ddmmyyyy format </span><span> * <span>@param <span>{Date Object}</span> dateObj </span></span><span> * <span>@returns <span>{String}</span> Date in ddmmyyyy format </span></span><span> */ </span> <span>dateToDDMMYYYY: function(dateObj) </span> <span>{ </span> <span>return (this.leadingZero(dateObj.getDate()) + this.leadingZero(dateObj.getMonth() + 1) + dateObj.getFullYear()).toString(); </span> <span>}, </span> <span>/** </span><span> * Takes a date string in dd/mm/yyyy format </span><span> * <span>@param <span>{String}</span> dateString Date in dd/mm/yyyy format </span></span><span> * <span>@returns <span>{Date Object}</span> Returns false if date sring is invalid </span></span><span> */ </span> <span>stringToDate: function(dateString) </span> <span>{ </span> <span>try </span> <span>{ </span> <span>var matches = dateString.match(/([0-9]{2})/([0-9]{2})/([0-9]{4})/); </span> <span>if(this.isValidDate(matches[3], matches[2], matches[1]) === false) </span> <span>{ </span> <span>return false; </span> <span>} </span> <span>return new Date(matches[3], parseInt(matches[2], 10)-1, parseInt(matches[1], 10)); </span> <span>} </span> <span>catch(e) </span> <span>{ </span> <span>return false; </span> <span>} </span> <span>}, </span> <span>/** </span><span> * Adds leading zero if passed value is single digit </span><span> * <span>@param <span>{String}</span> val </span></span><span> * <span>@returns <span>{String}</span> </span></span><span> */ </span> <span>leadingZero: function(val) </span> <span>{ </span> <span>var str = val.toString(); </span> <span>if(str.length == 1) </span> <span>{ </span> str <span>= '0' + str; </span> <span>} </span> <span>return str; </span> <span>}, </span> <span>/** </span><span> * Checks if return date is equal or after departure date </span><span> * <span>@param <span>{String}</span> departureDate </span></span><span> * <span>@param <span>{String}</span> returnDate </span></span><span> * <span>@returns <span>{Boolean}</span> </span></span><span> */ </span> <span>isDepartureReturnDateValid: function(departureDate<span>, returnDate</span>) </span> <span>{ </span> <span>var dep = this.stringToDate(departureDate); </span> <span>var ret = this.stringToDate(returnDate); </span> <span>if(dep > ret) </span> <span>{ </span> <span>return false; </span> <span>} </span> <span>return true; </span> <span>}, </span> <span>/** </span><span> * Detect whether the year supplied is a leap year </span><span> * <span>@param <span>{Integer}</span> year </span></span><span> * <span>@returns <span>{Boolean}</span> </span></span><span> */ </span> <span>isLeapYear: function(year) </span> <span>{ </span> year <span>= parseInt(year, 10); </span> <span>if(year % 4 == 0) </span> <span>{ </span> <span>if(year % 100 != 0) </span> <span>{ </span> <span>return true; </span> <span>} </span> <span>else </span> <span>{ </span> <span>if(year % 400 == 0) </span> <span>{ </span> <span>return true; </span> <span>} </span> <span>else </span> <span>{ </span> <span>return false; </span> <span>} </span> <span>} </span> <span>} </span> <span>return false; </span> <span>}, </span> <span>compareDates: function(<span>from, to</span>) </span> <span>{ </span> <span>var dateResult = to.getTime() - from.getTime(); </span> <span>var dateObj = {}; </span> dateObj<span>.weeks = Math.round(dateResult/(1000 * 60 * 60 * 24 * 7)); </span> dateObj<span>.days = Math.ceil(dateResult/(1000 * 60 * 60 * 24)); </span> dateObj<span>.hours = Math.ceil(dateResult/(1000 * 60 * 60)); </span> dateObj<span>.minutes = Math.ceil(dateResult/(1000 * 60)); </span> dateObj<span>.seconds = Math.ceil(dateResult/(1000)); </span> dateObj<span>.milliseconds = dateResult; </span> <span>return dateObj; </span> <span>}, </span> <span>compareDatesDDMMYYYY: function(<span>from, to</span>) </span> <span>{ </span> <span>from = from.split('/'); </span> <span>from = new Date(from[2], from[1], from[0]); </span> to <span>= to.split('/'); </span> to <span>= new Date(to[2], to[1], to[0]); </span> <span>return this.compareDates(from, to); </span> <span>}, </span> <span>/** </span><span> * Allow nice formatting of dates like PHP's Date function </span><span> * Derived from code written by Jac Wright at http://jacwright.com/projects/javascript/date_format </span><span> * <span>@param <span>{Date}</span> date JavaScript date object </span></span><span> * <span>@param <span>{String}</span> format Date format string </span></span><span> * <span>@returns <span>{String}</span> </span></span><span> */ </span> <span>format: function() </span> <span>{ </span> <span>var date, </span> format<span>, </span> args <span>= [].slice.call(arguments), </span> returnStr <span>= '', </span> curChar <span>= '', </span> months <span>= ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], </span> days <span>= ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], </span> methods <span>= </span> <span>{ </span> <span>// Day </span> <span>d: function() { return (date.getDate() < 10 ? '0' : '') + date.getDate(); }, </span> <span><span>D</span>: function() { return days[date.getDay()].substring(0, 3); }, </span> <span>j: function() { return date.getDate(); }, </span> <span>l: function() { return days[date.getDay()]; }, </span> <span><span>N</span>: function() { return date.getDay() + 1; }, </span> <span><span>S</span>: function() { return (date.getDate() % 10 == 1 && date.getDate() != 11 ? 'st' : (date.getDate() % 10 == 2 && date.getDate() != 12 ? 'nd' : (date.getDate() % 10 == 3 && date.getDate() != 13 ? 'rd' : 'th'))); }, </span> <span>w: function() { return date.getDay(); }, </span> <span>// Month </span> <span><span>F</span>: function() { return months[date.getMonth()]; }, </span> <span>m: function() { return (date.getMonth() < 9 ? '0' : '') + (date.getMonth() + 1); }, </span> <span><span>M</span>: function() { return months[date.getMonth()].substring(0, 3); }, </span> <span>n: function() { return date.getMonth() + 1; }, </span> <span><span>Y</span>: function() { return date.getFullYear(); }, </span> <span>y: function() { return ('' + date.getFullYear()).substr(2); }, </span> <span>// Time </span> <span>a: function() { return date.getHours() < 12 ? 'am' : 'pm'; }, </span> <span><span>A</span>: function() { return date.getHours() < 12 ? 'AM' : 'PM'; }, </span> <span>g: function() { return date.getHours() % 12 || 12; }, </span> <span><span>G</span>: function() { return date.getHours(); }, </span> <span>h: function() { return ((date.getHours() % 12 || 12) < 10 ? '0' : '') + (date.getHours() % 12 || 12); }, </span> <span><span>H</span>: function() { return (date.getHours() < 10 ? '0' : '') + date.getHours(); }, </span> <span>i: function() { return (date.getMinutes() < 10 ? '0' : '') + date.getMinutes(); }, </span> <span>s: function() { return (date.getSeconds() < 10 ? '0' : '') + date.getSeconds(); }, </span> <span>// Timezone </span> <span><span>O</span>: function() { return (-date.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(date.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(date.getTimezoneOffset() / 60)) + '00'; }, </span> <span><span>P</span>: function() { return (-date.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(date.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(date.getTimezoneOffset() / 60)) + ':' + (Math.abs(date.getTimezoneOffset() % 60) < 10 ? '0' : '') + (Math.abs(date.getTimezoneOffset() % 60)); }, </span> <span><span>T</span>: function() { var m = date.getMonth(); date.setMonth(0); var result = date.toTimeString().replace(<span>/<span>^.+ (?(<span>[^)]</span>+))?$</span>/</span>, ''); date.setMonth(m); return result;}, </span> <span><span>Z</span>: function() { return -date.getTimezoneOffset() * 60; }, </span> <span>// Full Date/Time </span> <span>c: function() { return date.format("Y-m-d") + "T" + date.format("H:i:sP"); }, </span> <span>r: function() { return date.toString(); }, </span> <span><span>U</span>: function() { return date.getTime() / 1000; } </span> <span>}; </span> <span>if(typeof this.getMonth == 'function') </span> <span>{ </span> date <span>= this; </span> format <span>= args[0]; </span> <span>} </span> <span>else </span> <span>{ </span> date <span>= args[0]; </span> format <span>= args[1]; </span> <span>} </span> <span>for(var i = 0; i < format.length; i++) </span> <span>{ </span> <span>var curChar = format.charAt(i); </span> <span>if(methods[curChar]) </span> <span>{ </span> returnStr <span>+= methods[curChar].call(); </span> <span>} </span> <span>else </span> <span>{ </span> returnStr <span>+= curChar; </span> <span>} </span> <span>} </span> <span>return returnStr; </span> <span>} </span> <span>}; </span> <span>JQUERY4U.DATETIME.init(); </span><span>})(jQuery);</span>
Frequently Asked Questions (FAQs) about JavaScript DateTime Functions
What is the difference between JavaScript Date() and new Date()?
In JavaScript, Date() and new Date() are used to work with dates and times. However, they function differently. When you use Date() as a function without the ‘new’ keyword, it returns the current date and time as a string. On the other hand, when you use new Date(), it returns a new Date object representing the current date and time.
How can I format a date in JavaScript?
JavaScript provides several methods to format a date. The most common method is to use the toDateString() function, which converts a date to a more readable format. You can also use methods like toLocaleDateString() or toISOString() to format the date according to the locale or in ISO standard format respectively.
How can I add or subtract days from a date in JavaScript?
To add or subtract days from a date in JavaScript, you can use the setDate() and getDate() methods. For example, to add 5 days to the current date, you would use the following code:
var date = new Date();
date.setDate(date.getDate() 5);
To subtract days, you would do the same but with a negative number.
How can I compare two dates in JavaScript?
In JavaScript, you can compare two dates using the standard comparison operators (==, !=, , =). However, it’s important to note that these operators compare the date objects, not the actual dates. To compare the dates themselves, you should convert them to a standard format, such as the number of milliseconds since the Unix Epoch (January 1, 1970), using the getTime() method.
How can I get the current time in JavaScript?
To get the current time in JavaScript, you can use the Date object’s methods. The simplest way is to create a new Date object without any arguments, which will represent the current date and time. Then, you can use methods like getHours(), getMinutes(), and getSeconds() to get the current time.
How can I convert a string to a date in JavaScript?
JavaScript’s Date object can parse strings into dates. You can pass the string to the Date constructor, and it will try to parse it. However, it’s important to note that the parsing depends on the format of the string, and it may not work as expected for all formats.
How can I get the day of the week in JavaScript?
JavaScript provides the getDay() method, which returns the day of the week as a number (0 for Sunday, 1 for Monday, and so on). To get the name of the day, you can create an array of names and use the number as an index.
How can I check if a year is a leap year in JavaScript?
To check if a year is a leap year in JavaScript, you can use a simple function that checks if the year is divisible by 4 but not by 100, unless it’s also divisible by 400. This is because leap years are every year that is evenly divisible by 4, except for years that are evenly divisible by 100. However, years that are evenly divisible by 400 are also leap years.
How can I get the difference between two dates in JavaScript?
To get the difference between two dates in JavaScript, you can subtract one date object from another. This will give you the difference in milliseconds. You can then convert this to days, hours, minutes, or seconds as needed.
How can I set a specific date and time in JavaScript?
To set a specific date and time in JavaScript, you can pass the year, month, day, hours, minutes, and seconds as arguments to the Date constructor. Note that the month is zero-based, so January is 0, February is 1, and so on.
The above is the detailed content of jQuery DATETIME Functions - Complete Listing. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

Clothoff.io
AI clothes remover

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

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

JavaScript's garbage collection mechanism automatically manages memory through a tag-clearing algorithm to reduce the risk of memory leakage. The engine traverses and marks the active object from the root object, and unmarked is treated as garbage and cleared. For example, when the object is no longer referenced (such as setting the variable to null), it will be released in the next round of recycling. Common causes of memory leaks include: ① Uncleared timers or event listeners; ② References to external variables in closures; ③ Global variables continue to hold a large amount of data. The V8 engine optimizes recycling efficiency through strategies such as generational recycling, incremental marking, parallel/concurrent recycling, and reduces the main thread blocking time. During development, unnecessary global references should be avoided and object associations should be promptly decorated to improve performance and stability.

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

Hello, JavaScript developers! Welcome to this week's JavaScript news! This week we will focus on: Oracle's trademark dispute with Deno, new JavaScript time objects are supported by browsers, Google Chrome updates, and some powerful developer tools. Let's get started! Oracle's trademark dispute with Deno Oracle's attempt to register a "JavaScript" trademark has caused controversy. Ryan Dahl, the creator of Node.js and Deno, has filed a petition to cancel the trademark, and he believes that JavaScript is an open standard and should not be used by Oracle

Which JavaScript framework is the best choice? The answer is to choose the most suitable one according to your needs. 1.React is flexible and free, suitable for medium and large projects that require high customization and team architecture capabilities; 2. Angular provides complete solutions, suitable for enterprise-level applications and long-term maintenance; 3. Vue is easy to use, suitable for small and medium-sized projects or rapid development. In addition, whether there is an existing technology stack, team size, project life cycle and whether SSR is needed are also important factors in choosing a framework. In short, there is no absolutely the best framework, the best choice is the one that suits your needs.

IIFE (ImmediatelyInvokedFunctionExpression) is a function expression executed immediately after definition, used to isolate variables and avoid contaminating global scope. It is called by wrapping the function in parentheses to make it an expression and a pair of brackets immediately followed by it, such as (function(){/code/})();. Its core uses include: 1. Avoid variable conflicts and prevent duplication of naming between multiple scripts; 2. Create a private scope to make the internal variables invisible; 3. Modular code to facilitate initialization without exposing too many variables. Common writing methods include versions passed with parameters and versions of ES6 arrow function, but note that expressions and ties must be used.

Promise is the core mechanism for handling asynchronous operations in JavaScript. Understanding chain calls, error handling and combiners is the key to mastering their applications. 1. The chain call returns a new Promise through .then() to realize asynchronous process concatenation. Each .then() receives the previous result and can return a value or a Promise; 2. Error handling should use .catch() to catch exceptions to avoid silent failures, and can return the default value in catch to continue the process; 3. Combinators such as Promise.all() (successfully successful only after all success), Promise.race() (the first completion is returned) and Promise.allSettled() (waiting for all completions)

CacheAPI is a tool provided by the browser to cache network requests, which is often used in conjunction with ServiceWorker to improve website performance and offline experience. 1. It allows developers to manually store resources such as scripts, style sheets, pictures, etc.; 2. It can match cache responses according to requests; 3. It supports deleting specific caches or clearing the entire cache; 4. It can implement cache priority or network priority strategies through ServiceWorker listening to fetch events; 5. It is often used for offline support, speed up repeated access speed, preloading key resources and background update content; 6. When using it, you need to pay attention to cache version control, storage restrictions and the difference from HTTP caching mechanism.
