Sort out some JavaScript time processing extended functions

Source: Internet
Author: User
Tags month name

In JavaScript, time processing is often used. Recently, I want to build my own code library, sort out several js processing time functions that I used earlier, and share them with you. The code library will be added and modified in the future.

Converts a string to a date object.

Sometimes the string needs to be converted to a Date object, but the new Date ("") is not supported in IE to instantiate a Date object, which is supported in ff, so an extension function is written, converts a string such as yyyy-mm-dd Or dd/mm/yyyy to a date object. The Code is as follows:

/* Function: convert a string to a string in the format of yyyy-mm-dd Or dd/mm/yyyy. Return the Date object. Note: in IE, Date objects cannot be directly instantiated, such as new Date ("") */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 07 2011 17:30:58 GMT + 0800

Calculate the difference between two dates

This function can calculate the difference between two dates (millisecond/Second/minute/hour/day), mainly using the getTime () function and Math. floor () function, the Code is as follows:

/* Function: calculate the difference parameter between two dates: date is the date object flag: ms-millisecond, s-second, m-minute, h-hour, d-Day, m-month, y-year return: the difference between the current date and Date in milliseconds/Second/minute/hour/day */date. prototype. dateDiff = function (date, flag) {var msCount; var diff = this. getTime ()-date. getTime (); switch (flag) {case "ms": msCount = 1; break; case "s": msCount = 1000; break; case "m ": msCount = 60*1000; break; case "h": msCount = 60*60*1000; break; case "d": msCount = 24*60*60*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>
Determines whether a year is a leap year.
/* Function: determines whether a year is a leap year. Return Value: whether it is a leap year */Date. prototype. isLeapYear = function () {var year = this. getFullYear (); return (year % 4 = 0) & (year % 100! = 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
Format date

This function was searched from the Internet and slightly modified. It is similar to the Format function in. net, and the formatted string such as "yyyy-MM-dd" is passed in. net. The formatted date is returned.

/* Function: format the date parameter: formatStr-Format String d: displays the day as a number without leading zero, for example, 1dd: displays the day as a number with leading zero, for example, 01ddd: display the day as an abbreviation, for example, Sundddd: display the day as the full name, for example, SundayM: displays the month as a number without leading zero, for example, 1 MM: display the month as a number with leading zeros, for example, 01MMM: display the month as an abbreviation, for example, JanMMMM: display the month as the full month name, such as Januaryyy: yyyy: yyyy: use the 12-hour system to display the hour as a digit with a leading zero. Use the 24-hour system to display the hour as a digit without a leading zero. HH: use the 24-hour system to display the hour as a number m with a leading zero: display the minute as a number mm without a leading zero: display the minute as a number s with a leading zero: display second as a number without leading zero ss: Display second as a number with leading zero l: Display millisecond as a number without leading zero l L: display the data in milliseconds as a number with leading zeros. tt: Show am/pmTT: Show AM/PM. Return: formatted Date */Date. prototype. format = function (formatStr) {var date = this;/* function: Fill 0 character parameter: value-string to be filled, length-total length returned: filled 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 ($0) {switch ($0) {case 'D': return date. getDate (); case 'dd': return zeroize (date. getDate (); case 'ddd ': return ['sun', 'mon', 'tue ', 'wed', 'thr', 'fri ', 'sat '] [date. getDay ()]; case 'ddddd': return ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'Friday ', 'saturday'] [date. getDay ()]; case 'M': return date. getMonth () + 1; case 'mm': return zeroize (date. getMonth () + 1); case 'Mmm': return ['Jan ', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug ', 'sept', 'oct', 'nov', 'dec '] [date. getMonth ()]; case 'mmmm': return ['january ', 'february', 'march', 'marril', '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. getH Ours () % 12 | 12; case 'hh': return zeroize (date. getHours () % 12 | 12); case 'H': return date. getHours (); case 'hh': return zeroize (date. getHours (); 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 (); ca Se '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> // result: // 10:13:37

In the future work and study, your code library will be constantly added and improved. Please advise if you have any questions.

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.