jQuery DATETIME Functions - Complete Listing
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

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

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 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.

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.

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.

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.

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

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.

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.

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
