Share your own written JS version of the date formatting and parsing tool class, absolutely easy to use!

Source: Internet
Author: User
Tags date1 parse string

Objective

Originally wanted to imitate the Java inside of the SimpleDateFormat() object, but feel this use is inconvenient, so or directly write a separate method to forget.

Original link

Date formatting usage instructions

FormatDate (date, FMT), where FMT supports the following formats:

    • Y (year)
    • M (month)
    • D (Sun)
    • Q (quarterly)
    • W (week)
    • H (24 hour hour)
    • H (12 Hour hour)
    • M (min)
    • S (sec)
    • S (MS)

In addition, the number of characters determines the length of the output character, such as output, output, output Friday, output yy yyyy ww www Friday, and so on.

Code

Complete code altogether 30 lines:

/** * Formatting a date into a string of the specified format * @param date to format, not the default current time, or a timestamp * @param fmt destination string format, supported characters are: Y,m,d,q,w,h,h,m,s, Default: Yyyy-mm-dd HH:MM:SS * @returns returns the formatted date string */function formatdate (date, fmt) {date = date = undefined? New Date ()    : date; Date = typeof Date = = ' number '?    New Date (date): date; FMT = FMT | |    ' Yyyy-mm-dd HH:mm:ss ';        var obj = {' Y ': date.getfullyear (),//year, note must be used with getFullYear ' M ': date.getmonth () + 1,//month, note is from 0-11 ' d ': date.getdate (),//Date ' Q ': Math.floor ((Date.getmonth () + 3)/3),//Quarterly ' W ': Date.getday (),//week, note is 0-6 ' h ': date.gethours (),//24-hour ' H ': date.gethours ()% 12 = = 0? 12:date.gethours ()% 12,//12 Hour system ' m ': date.getminutes (),//min ' s ': date.getseconds (),//sec ' s ': D    Ate.getmilliseconds ()//msec};    var week = [' Day ', ' one ', ' two ', ' three ', ' four ', ' five ', ' six ']; for (var i in obj) {FMT = Fmt.replace (new RegExp (i+ ' + ', ' g '), function (m) {var val = obj[i] + ‘‘; if (i = = ' W ') return (M.length > 2?)            ' Week ': ' Week ') + week[val];            for (var j = 0, Len = val.length; J < M.length-len; J + +) val = ' 0 ' + val; return m.length = = 1?        Val:val.substring (val.length-m.length);    }); } return FMT;}

  

Using the example
FormatDate (); 2016-09-02 13:17:13formatdate (New Date (), ' yyyy-mm-dd '); 2016-09-02//2016-09-02 3rd Quarter Friday 13:19:15:792formatdate (New Date (), ' yyyy-mm-dd first q quarter www HH:mm:ss:SSS '); FormatDate ( 1472793615764); 2016-09-02 13:20:15

  

Date Resolution Description

Parsedate (str, FMT), wherein FMT supports the following formats:

    • Y (year)
    • M (month)
    • D (Sun)
    • H (24 hour hour)
    • H (12 Hour hour)
    • M (min)
    • S (sec)
    • S (MS)
Full code

Complete code total 17 lines:

/** * Parse string into date * @param str input date string, such as ' 2014-09-13 ' * @param fmt string format, default ' YYYY-MM-DD ', supported as follows: Y, M, D, H, M, s, S, not supported W and Q * @returns Parsed Date type dates */function parsedate (str, FMT) {    FMT = FMT | | ' Yyyy-mm-dd ';    var obj = {y:0, m:1, d:0, h:0, h:0, m:0, s:0, s:0};    Fmt.replace (/([^ymdhmss]*?) (([YMDHMSS]) \3*) ([^ymdhmss]*?) /g, function (m, $, $, $ $, $4, IDX, old)    {        str = str.replace (new RegExp ($1+ ' \\d{'}) ' +$2.length+ '), function ( _m, _$1)        {            obj[$3] = parseint (_$1);            return ';        });        return ';    });    Obj. m--; The month is starting at 0, so subtract 1    var date = new Date (obj.y, obj. M, OBJ.D, obj. H, OBJ.M, OBJ.S);    if (obj. S!== 0) date.setmilliseconds (obj. S); If the millisecond    return date is set;}

  

Sample code
Parsedate (' 2016-08-11 '); Thu 00:00:00 gmt+0800parsedate (' 2016-08-11 13:28:43 ', ' yyyy-mm-dd HH:mm:ss ')//Thu 13:28:43 GM t+0800

  

Other date-related methods

Others have simply encapsulated several methods, which are simply affixed together, including the above:

/** * ===================================== * Date-dependent method * ===================================== */;(function ($) {$.extend ({/** *) formats the date as a string in the specified format * @param date to be formatted, the default current time, or a timestamp * @para M FMT target string format, supported characters are: y,m,d,q,w,h,h,m,s, default: Yyyy-mm-dd HH:MM:SS * @returns return formatted date String */FormatDate            : function (date, FMT) {date = date = = undefined? New Date (): date; Date = typeof Date = = ' number '?            New Date (date): date; FMT = FMT | |            ' Yyyy-mm-dd HH:mm:ss '; var obj = {' Y ': date.getfullyear (),//year, note must be getFullYear ' M ': Date.getmonth () + 1,//month, note is from 0-11 ' d ': date.getdate (),//Date ' Q ': Math.floor ((Date.getmonth () + 3)/3),/ /Quarter ' W ': Date.getday (),//week, note Yes 0-6 ' h ': date.gethours (),//24-hour ' h ': Dat E.gethours ()% 12 = = 0? 12:date.gethours ()% 12,//12-hour ' m ': date.getminutes (),//minute ' s ': date.getseconds (),//sec ' s ': date.ge            Tmilliseconds ()//msec};            var week = [' Day ', ' one ', ' two ', ' three ', ' four ', ' five ', ' six '];                    for (var i in obj) {FMT = Fmt.replace (new RegExp (i+ ' + ', ' g '), function (m) {                    var val = obj[i] + "; if (i = = ' W ') return (M.length > 2?)                    ' Week ': ' Week ') + week[val];                    for (var j = 0, Len = val.length; J < M.length-len; J + +) val = ' 0 ' + val; return m.length = = 1?                Val:val.substring (val.length-m.length);            });        } return FMT; },/** * Parse string into date * @param str input date string, such as ' 2014-09-13 ' * @param fmt string format, default ' YYYY-MM-DD ', support            As follows: Y, M, D, H, M, S, S, W and Q * are not supported @returns date type dates after parsing */parsedate:function (str, FMT) { FMT = FMT | |            ' Yyyy-mm-dd '; VAr obj = {y:0, m:1, d:0, h:0, h:0, m:0, s:0, s:0}; Fmt.replace (/([^ymdhmss]*?) (([YMDHMSS]) \3*) ([^ymdhmss]*?) /g, function (m, $, $, $ $, $4, IDX, old) {str = str.replace (new RegExp ($1+ ' \\d{'}                    ) ' +$4 ', function (_m, _$1) {obj[$3] = parseint (_$1);                Return ';                });            Return ';            }); Obj. m--; The month is starting at 0, so subtract 1 var date = new Date (obj.y, obj. M, OBJ.D, obj.            H, OBJ.M, OBJ.S); if (obj. S!== 0) date.setmilliseconds (obj. S);        If the milliseconds return date is set;         },/** * format a date into a friendly format, for example, return "just" within 1 minutes, * return time of day, return day of the year, otherwise, return month Day * @param {Object} date            */formatdatetofriendly:function (date) {date = date | | new Date (); Date = typeof Date = = = ' Number '?            New Date (date): date;            var now = new Date (); if ((Now.gettime ()-Date.getTime ()) < 60*1000) return ' just ';            1 minutes or less as "just" var temp = this.formatdate (date, ' yyyy year M d ');            if (temp = = This.formatdate (now, ' yyyy year M d ')) return this.formatdate (date, ' hh:mm ');            if (date.getfullyear () = = Now.getfullyear ()) return this.formatdate (date, ' m ' D Day ');        return temp;          },/** * Converts a length of time into a friendly format, such as: * 147-> "2 minutes 27 seconds" * 1581-> "26 minutes 21 seconds" * 15818-> "4 hours 24 minutes" * @param {Object} second */Formatdurationtofriendly:function (second) {if (Seco            nd <) return second + ' s ';            else if (second < 60*60) return (second-second%60)/60+ ' Sub ' +second%60+ ' seconds ';            else if (second < 60*60*24) return (second-second%3600)/60/60+ ' hours ' +math.round (SECOND%3600/60) + ' points ';        Return (SECOND/60/60/24). toFixed (1) + ' Day ';  },/** * Converts time into mm:ss form */formattimetofriendly:function (second) {var m = Math.floor (SecoND/60); m = m < 10?            (' 0 ' + m): M;            var s = second% 60; s = S < 10?            (' 0 ' + s): s;        return m + ': ' + S;  },/** * To determine whether a year is a leap years * @param year can be a date type or an int type, not the default current time */isleapyear:            function (year) {if [year = = undefined] year = new Date ();            if (year instanceof Date) year = Year.getfullyear (); Return (year% 4 = = 0 && Year% 100! = 0) | |        (Year% 400 = = 0);         },/** * Gets the total number of days in a certain January of a year, without any parameters, gets the current month's * mode one: $.getmonthdays ();         * Method Two: $.getmonthdays (new Date ());         * Way Three: $.getmonthdays (2013, 12);            */getmonthdays:function (date, month) {var y, m;            if (date = = undefined) Date = new Date ();                if (date instanceof date) {y = Date.getfullyear ();            m = Date.getmonth (); } else if (typeof date = = ' NumbeR ') {y = date;            m = month-1; } var days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];            Number of days per month for non-leap years//If it is a leap year and is February if (m = = 1 && this.isleapyear (y)) return days[m]+1;        return days[m];         },/** * Calculates the number of days between 2nd, using a method that compares the number of milliseconds * The date passed in is either date type, or the string date in YYYY-MM-DD format * @param date1 date One             * @param date2 Date Two */Countdays:function (date1, date2) {var fmt = ' Yyyy-mm-dd ';            Convert date to string, the purpose of the conversion is to remove "hours, minutes, seconds" if (date1 instanceof date && date2 instanceof date)                {date1 = This.format (FMT, date1);            Date2 = This.format (FMT, date2); } if (typeof date1 = = = ' String ' && typeof date2 = = = ' String ') {date1 = THIS.P                Arse (date1, FMT);                Date2 = This.parse (Date2, FMT); Return (Date1.gettime ()-Date2.gettime ())/(1000*60*60*24); } else {console.error (' parameter format is invalid!                ‘);            return 0; }        }    });}) (JQuery);

Personal website: http://liuxianan.com
Blog Park: Http://www.cnblogs.com/liuxianan
Weibo: Http://weibo.com/liuxianan
copyright©2016 Xiao Ming Students

Share your own written JS version of the date formatting and parsing tool class, absolutely easy to use!

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.