Organize some JavaScript time processing extension functions

Source: Internet
Author: User
Tags month name

In JavaScript, time processing is often needed. Recently want to slowly build their own code base, sorting out a few of the previously used JS processing time functions, sent to share with you, later in the use will continue to add and modify the code base.

Convert a string to a Date object

Sometimes it is necessary to convert a string to a Date object, but IE does not support new date ("2011-04-07") to instantiate date objects, FF support, so write an extension function to convert a string such as YYYY-MM-DD or dd/mm/yyyy into a Date object. The code is as follows: Lanxi County Quwan Home Photography

/* Function: Converts a string to a Date object parameter: A string in the form of YYYY-MM-DD or DD/MM/YYYY returns: Date Object note: The direct instantiation of a Date object, such as new date ("2011-04-06") is not supported in IE * * Date.prototype.convertDate = function (date) {var flag = True;var Datearray = Date.split ("-"); if (datearray.length! = 3) { Datearray = Date.split ("/"); if (datearray.length! = 3) {return null;} Flag = false;} var newdate = new Date (), if (flag) {//month starts from 0 newdate.setfullyear (datearray[0], datearray[1]-1, datearray[2]);} else {newdate.setfullyear (datearray[2], datearray[1]-1, datearray[0]);} Newdate.sethours (0, 0, 0); return newdate;};

Test:

<script type= "Text/javascript" > Document.writeln (New Date (). Convertdate ("7/12/2011"));</script>

Output: Wed Dec 17:30:58 gmt+0800

Calculates the difference between two dates

This function calculates the difference (milliseconds/second/minute/hour/day) before the two date, mainly using the gettime () function and the Math.floor () function, the code is as follows:

/* Function: Calculates the difference parameter between the two dates: date is a DateTime object flag:ms-milliseconds, S-second, M-Min, H-hour, D-Day, M-month, Y-year return: current date and date two milliseconds per second/minute/hour/day */ Date.prototype.dateDiff = function (date, flag) {var mscount;var diff = this.gettime ()-date.gettime (); switch (flag) {CAs E "MS": Mscount = 1;break;case "s": Mscount = 1000;break;case "M": Mscount = * 1000;break;case "h": Mscount = 60 * 60 * 100 0;break;case "D": Mscount = $ * * 1000;break;} return Math.floor (Diff/mscount);};

Test:

<script type= "Text/javascript" > var d1 = new Date (). Convertdate ("2011-04-08");  var d2 = new Date (). Convertdate ("2011-04-07"); Document.writeln (D1.datediff (D2, ' d '));</script>
Determine if a year is a leap years
/* Function: Determine if a year is a leap years return: Whether it is a leap month */date.prototype.isleapyear = function () {var year = this.getfullyear (); return (4 = = 0) &A mp;& (year%!! = 0 | | year% 400 = = 0);}

Test:

<script type= "Text/javascript" > Document.writeln (New Date (). Convertdate ("2000-04-08"). Isleapyear () + ""); Document.writeln (New Date (). Convertdate ("2011-04-08"). Isleapyear () + ""); </script>//Result://true//False
Formatted date

This function was searched from the Internet, slightly modified, it is similar to the Format function in. NET, passing in a formatted string such as "Yyyy-mm-dd", returning the formatted date.

/* Function: Format date parameter: formatstr-format string D: Displays the day as a number without leading zeros, such as 1DD: Displays the day as a number with leading zeros, such as 01ddd: Displays the day as an abbreviated form, such as SUNDDDD: Displays the day as the full name, such as Sundaym: Displays the month as a number without leading zeros, as shown in January as 1MM: Displays the month as a number with leading zeros, such as 01MMM: Displays the month as an abbreviated form, such as janmmmm: Displays the month as the full month name, such as januaryyy: Displays the year in two-digit format yyyy: Year in four-digit format h: Displays the hour as a number without leading zeros using a 12-hour system Note | | Usage hh: Displays the hour as a number h with leading zeros using a 12-hour system: Use a 24-hour system to display the hour as a number without leading zeros hh: Displays the hour as a number m with leading zeros using a 24-hour system: Displays the minute as a number with no leading zeros mm: Displays the minute as a number s with leading zeros: Displays the second as a number SS without leading zeros : Displays seconds as a leading zero number L: Displays milliseconds as a number without leading zeros ll: Displays milliseconds as a number with leading zeros TT: Display AM/PMTT: Show AM/PM return: formatted date */date.prototype.format = function (  FORMATSTR) {var date = this;/* function: Padding 0-character argument: value-the string to fill, length-total length returned: The populated string */var zeroize = function (value, length) {if (!length) {length = 2;} Value = new String (value), for (var i = 0, zeros = "; I < (length-value.length); i++) {zeros + = ' 0 ';} return zeros + value;}; return Formatstr.replace (/"[^"]* "|" [^ ']* ' |\b (?:d {1,4}| M{1,4}|yy (?: yy)? | ([HHMSTT]) \1?| [LLZ]) \b/g, function ($) {switch ($) {case ' d ': return Date.getdate (); case ' DD ': Return Zeroize (Date.getdate ()); case ' DDD ': RET urn [' Sun ', ' Mon ', ' Tue ', ' Wed ', ' Thr ', ' Fri ', ' Sat '][date.getday ()];case ' dddd ': return [' Sunday ', ' Monday ', ' Tuesday ', ' Wednesday ', ' Thursday ', ' Frida ' Y ', ' Saturday '][date.getday ()];case ' m ': return Date.getmonth () + 1;case ' MM ': Return Zeroize (Date.getmonth () + 1); case ' m MM ': return [' Jan ', ' Feb ', ' Mar ', ' Apr ', ' may ', ' June ', ' Jul ', '][date.getmonth ', ' Sep ', ' Oct ', ' Nov ', ' Dec ' ()];case ' MM  MM ': return [' January ', ' February ', ' March ', ' April ', ' may ', ' June ', ' July ', ' August ', ' September ', ' October ', ' November ', ' December '][date.getmonth ()];case ' yy ': return new String (Date.getfullyear ()). substr (2); case ' yyyy ': return Date.getfullyear (); case ' H ': return date.gethours ()% 12 | | 12;case ' hh ': Return Zeroize (date.gethours ()% | |), case ' H ': Return date.gethours (), Case ' hh ': Return zeroize (date.g Ethours ()); case ' m ': Return Date.getminutes (), Case ' mm ': Return Zeroize (Date.getminutes ()), case ' s ': return Date.getseconds (); case ' SS ': Return Zeroize (Date.getseconds ()), Case ' l ': return Date.getmilliseconds (), Case ' ll ':Return Zeroize (Date.getmilliseconds ()); case ' TT ': Return date.gethours () < 12? ' Am ': ' PM '; case ' TT ': Return date.gethours () < 12? ' AM ': ' PM ';}});

Test:

<script type= "Text/javascript" > Document.writeln (New Date (). Format ("Yyyy-mm-dd hh:mm:ss"); </script>// Results://2011-04-08 10:13:37

Organize some JavaScript time processing extension functions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.