JavaScript date formatting and parsing __javascript

Source: Internet
Author: User
Tags locale

JavaScript development often needs to convert dates, turn dates into strings, or generate dates from strings. JavaScript date objects have built-in simple date formatting methods ToString () and Date resolution Method Date.parse (), which have greater limitations and cannot customize the format of custom date formatting and parsing strings. Listed below are some common date processing JS libraries.

name Description
Xdate Xdate the JAVASCIRPT local Date object, which provides enhanced functionality for date resolution, formatting, and other operations, and implements the same method for the local date object.
Https://github.com/arshaw/xdate
Moment.js Moment.js is an easy-to-use, lightweight JavaScript date-processing library that provides features such as date formatting, date resolution, and more.
Https://github.com/moment/moment
Date.js Date.js is an open source JavaScript date library that parses, formats, and processes date data and supports the processing of date formats in multiple languages. Date.js official website is no longer updated, in GitHub can find maintenance version
Https://github.com/abritinthebay/datejs

The above JS Date Library provides the function of date parsing and formatting, if the date is only formatted and parsed, the following provides a more lightweight approach.

/** * Date formatting and parsing * Dateutils provides format and parse for date conversion.
 * Format (date, pattern) formats the date as a string.
 * Use method: * var date = new Date (); * Dateutils.format (date, ' Yyyy-mm-dd HH:mm:ss ');
 2015-08-12 13:00:00 * * Parse (str, pattern) turns the string into a date.
 * Use method: * var str = 2015-08-12 13:00:00;
 * Dateutils.format (str, ' yyyy-mm-dd HH:mm:ss ');
 * * Parse has two parameters, and if only the STR parameter is passed, the browser-built Date.parse () method is invoked to convert. * * Format description *-----------------------------------------------------------------------* yy year after two digits, such as
 2015 the latter two digits are 15.
 * YYYY year four digits.
 * M month, take the value 1 ~ 12.
 * MM month, take the value 01 ~ 12, if the month is single-digit, the front complement 0.
 * MMM month abbreviation, such as the January English abbreviation for a short, Chinese abbreviation for one.
 * MMMM Month full name, such as January, January.
 * d is the day ordinal of the month, and the value 1~31.
 * DD Date in the month of the first day, the value 01~31, if the number of days in Single-digit, the front of 0.
 * DDD week abbreviation, take duty, one or two, three or four, five or six.
 * dddd Week full name, take value Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday.
 * H 24-hour system, value 0~23.
 * HH 24-hour system, the value of 00~23, if the hour is single-digit, the front of 0.
 * H 12-hour system, value 0~11. * HH 12-hour system, take value 00~11, if smallFor single-digit digits, the front is 0.
 * M minutes, take value 0~59.
 * mm minutes, take the value of 00~59, if the single digit, the front of the 0.
 * s seconds, take value 0~59.
 * ss seconds, take the value of 00~59, if the single digit, the front of 0.
 * S milliseconds, take value 0~999.
 * SS millisecond, take value 00~999, if less than two digits, the front of 0.
 * SSS milliseconds, take the value 000~999, if less than three digits, the front of 0.
 * t morning, afternoon abbreviation.
 * TT morning, afternoon full name.   *-----------------------------------------------------------------------* * @author accountwcx@qq.com * @date 2015-08-12 */Dateutils = (function () {/* var locale = {daynames: ["Sunday", "Monday", "Tuesday", "Wedne
        Sday "," Thursday "," Friday "," Saturday "], shortdaynames: [" Sun "," Mon "," Tue "," Wed "," Thu "," Fri "," Sat "], MonthNames: ["January", "February", "March", "April", "may", "June", "July", "August", "September", "October", "November "," December "], Shortmonthnames: [" The "," Feb "," Mar "," APR "," may "," June "," O "," Aug "," Sep "," Oct "," Nov "," De C ", am: ' am ', pm: ' PM ', Shortam: ' A ', SHORTPM: ' P'
    }; * * var locale = {daynames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], shortdaynames: ["Day", ""] One "," two "," three "," four "," five "," six "], MonthNames: [" January "," February "," March "," April "," May "," June "," July "," August "," September "," October "," November "," December "  "], Shortmonthnames: [" One "," two "," three "," four "," five "," six "," seven "," eight "," Nine "," Ten "," 11 "," 12 "], am:" a.m. ", PM:

    "Afternoon", Shortam: ' On ', SHORTPM: ' Next '};

        /** * Left complement 0/function Leftpad (str, size) {var result = ' + str;
        while (Result.length < size) {result = ' 0 ' + result;
    return result;          var Parsetoken = (function () {var match2 =/\d{2}/,//00-99//MATCH3 =/\d{3}/,
            000-999 MATCH4 =/\d{4}/,//0000-9999 Match1to2 =/\d{1,2}/,//0-99
        Match1to3 =/\d{1,3}/,//0-999//match1to4 =/\d{1,4}/,//0-9999    match2w =/. {2}/,//Match two characters match1wto2w =/. {1,2}/,///match 1~2 Character Map = {//year's after two-bit ' yy ': {regex:match 2, Name: ' Year '},//Years ' yyyy ': {r 
                    EGEX:MATCH4, Name: ' Year '},//Two-digit month, 0 ' MM ' in less than two digits: {
                REGEX:MATCH2, Name: ' Month '},//month ' M ': {regex:match1to2, Name: ' Month '},//two digits Date with less than two digits for 0 ' dd ': {REGEX:MATCH2, Name: ' Date '}
                ,//Date ' d ': {regex:match1to2, Name: ' Date '
        },///two-digit hour, 24-hour ' HH ': {            REGEX:MATCH2, Name: ' Hours '},//hour, 24-hour system ' H ': {regex:match1to2, Name: ' Hours '},///two digits
                Hours, 12 hours into the system ' hh ': {regex:match2, Name: ' Hours '}, 
                Hours, 12 hours into the system ' H ': {regex:match1to2, Name: ' Hours '
                    },//Two-digit minute ' mm ': {REGEX:MATCH2,
                    Name: ' Minutes '},//min ' m ': {Regex:match1to2,
                    Name: ' Minutes '}, ' s ': {Regex:match1to2,
                    Name: ' Seconds '}, ' ss ': {REGEX:MATCH2,
     Name: ' Seconds '           },//a.m., PM ' TT ': {regex:match2w, name
                    : ' t '},//a.m., PM ' t ': {regex:match1wto2w,
                    Name: ' t '},//Millisecond ' S ': {Regex:match1to3,
                    Name: ' Millisecond '},//MS ' SS ': { Regex:match1to3, Name: ' Millisecond '},//MS ' SSS ':

        {REGEX:MATCH1TO3, Name: ' Millisecond '}};
            return function (token, str, dateobj) {var result, part = Map[token];
                if (part) {result = Str.match (Part.regex);
                    if (result) {Dateobj[part.name] = result[0]; return result[0];
                } return null;
    };

    })(); return {Locale:locale, format:function (val, pattern) {if (Object.prototype.toString.call) (Val
            !== ' [object Date] ') {return '; } if (Object.prototype.toString.call (pattern)!== ' [Object String] ' | | | = = = = = ') {patter
            n = ' yyyy-mm-dd HH:mm:ss '; var fullyear = Val.getfullyear (), month = Val.getmonth (), day = Val.getday ( ), date = Val.getdate (), hours = Val.gethours (), minutes = Val.getminutes (

            ), seconds = Val.getseconds (), milliseconds = Val.getmilliseconds (); return pattern.replace (/\ \)? ( dd?d?d?| Mm? M? m?| yy?y?y?| hh?| hh?| mm?| ss?| tt?| Ss? S?)
                /g, function (m) {if (M.charat (0) = = ' \ ') {return m.replace (' \ \ ');

 }               var locale = Dateutils.locale; Switch (m) {case ' hh ': Return Leftpad (Hours < 13?)
                    (hours = 0 12:hours): (hours-12), 2); Case "H": return hours < 13?
                    (Hours = = 0 12:hours): (hours-12);
                    Case "HH": Return Leftpad (Hours, 2);
                    Case "H": return hours;
                    Case "MM": Return Leftpad (minutes, 2);
                    Case "M": return minutes;
                    Case "SS": Return Leftpad (seconds, 2);
                    Case "S": return seconds;
                    Case "yyyy": return fullyear;
                    Case "yy": Return (Fullyear + "). substring (2);
                 Case "dddd":       return Locale.daynames[day];
                    Case "DDD": return Locale.shortdaynames[day];
                    Case "DD": Return Leftpad (date, 2);
                    Case "D": return date;
                    Case "MMMM": return Locale.monthnames[month];
                    Case "MMM": return Locale.shortmonthnames[month];
                    Case "MM": Return Leftpad (month + 1, 2);
                    Case "M": Return month + 1; Case "T": return hours < 12?
                    Locale.shortAm:locale.shortPm; Case "TT": Return hours < 12?
                    locale.am:locale.pm;
                    Case "S": return milliseconds;
            Case "SS": Return Leftpad (milliseconds, 2);        Case "SSS": Return Leftpad (milliseconds, 3);
                Default:return m;
        }
            });
            }, Parse:function (val, pattern) {if (!val) {return null;
                } if (Object.prototype.toString.call (val) = = ' [Object Date] ') {//If Val is a date, return.
            return Val;
                } if (Object.prototype.toString.call (val)!== ' [Object String] ') {//If Val is not a string, exit.
            return null;
            var time; 
                if (Object.prototype.toString.call (pattern)!== ' [Object String] ' | | | = = = = = ') {//If FMT is not a string or an empty string.
                Use the browser's built-in date resolution time = Date.parse (val);
                if (isNaN) {return null;
            Return to New Date (time); 
  var i, token, tmpval,              Tokens = Pattern.match (/(\)? dd?| mm?| yy?y?y?| hh?| hh?| mm?| ss?| tt?| Ss? s?|.)
                    /g), Dateobj = {year:0, month:1, date:0, hours:0, minutes:0, seconds:0, Milliseco

            ND:0};
                for (i = 0; i < tokens.length i++) {token = tokens[i];

                Tmpval = Parsetoken (token, Val, dateobj); if (tmpval!== null) {if (Val.length > Tmpval.length) {val = val.substring (tm
                    Pval.length);
                    }else{val = ';
                }}else{val = val.substring (token.length); } if (dateobj.t) {if (DateUtils.locale.pm = = DATEOBJ.T | | DateUtils.locale.shortPm = = dateobj.t) {dateobj. Hours = (+dateobj.hours) + 12;

            } Dateobj.month-= 1; return new Date (Dateobj.year, Dateobj.month, Dateobj.date, Dateobj.hours, Dateobj.minutes, Dateobj.seconds,
        Dateobj.millisecond);
}
    }; })();
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.