Click here to Skip to main content
11,482,039 members (65,746 online)
Click here to Skip to main content

Date and Time formatting in JavaScript like .Net C# or VB.Net

, 19 May 2014 CPOL 13.7K 234 31
Rate this:
Please Sign up or sign in to vote.
Custom Date and Time formatting in javascript like on .Net C# or VB.Net
Download DateFormat-JavaScript.zip - 3 KB

Introduction

A date and time format string defines the text representation of a Date() object, that results a custom format string. Any string that is not a standard date and time format string is interpreted as a custom date and time format string.

You can download the format.date JavaScript Utility, an application that enables you to apply format strings to date and time values and displays the result in string format.

Background

In formatting operations, custom date and time format strings can be used with the format method of a Date() instance.

The format method require that an input string conform exactly to a particular pattern for the parse operation to succeed otherwise it will gives you an error (e.g. ERROR: Not supported method [method name]).

The following table describes the custom date and time format and displays a result string produced by each format.

FormatDescriptionDate ExampleOutput
"d" The day of the month, from 1 through 31.5/1/2014 1:45:30 PM 1
"dd"The day of the month, from 01 through 31. 5/1/2014 1:45:30 PM01
"ddd"The abbreviated name of the day of the week. 5/15/2014 1:45:30 PMThu
"dddd"The full name of the day of the week. 5/15/2014 1:45:30 PMThursday
"f"The tenths of a second in a date and time value. 5/15/2014 13:45:30.6176
"ff"The hundredths of a second in a date and time value 5/15/2014 13:45:30.61761
"fff"The milliseconds in a date and time value. 5/15/2014 13:45:30.617617
"F"If non-zero, the tenths of a second in a date and time value. 5/15/2014 13:45:30.6176
"FF" If non-zero, the hundredths of a second in a date and time value. 5/15/2014 13:45:30.61761
"FFF"If non-zero, the milliseconds in a date and time value. 5/15/2014 13:45:30.617617
"h"The hour, using a 12-hour clock from 1 to 12. 5/15/2014 1:45:30 AM1
"hh"The hour, using a 12-hour clock from 01 to 12. 5/15/2014 1:45:30 AM01
"H"The hour, using a 24-hour clock from 0 to 23. 5/15/2014 1:45:30 AM1
"HH"The hour, using a 24-hour clock from 00 to 23. 5/15/2014 1:45:30 AM01
"m"The minute, from 0 through 59. 5/15/2014 1:09:30 AM9
"mm"The minute, from 00 through 59. 5/15/2014 1:09:30 AM09
"M"The month, from 1 through 12. 5/15/2014 1:45:30 PM6
"MM"The month, from 01 through 12. 5/15/2014 1:45:30 PM06
"MMM"The abbreviated name of the month. 6/15/2014 1:45:30 PMJun
"MMMM"The full name of the month. 6/15/2014 1:45:30 PMJune
"s"The second, from 0 through 59. 5/15/2014 1:45:09 PM9
"ss"The second, from 00 through 59. 5/15/2014 1:45:09 PM09
"t"The first character of the AM/PM designator. 5/15/2014 1:45:09 PMP
"tt"The AM/PM designator. 5/15/2014 1:45:09 PMPM
"y"The year, from 0 to 99. 5/15/2014 1:45:09 PM9
"yy"The year, from 00 to 99. 5/15/2014 1:45:09 PM09
"yyy"The year, with a minimum of three digits. 5/15/2009 1:45:30 PM2009
"yyyy"The year as a four-digit number. 5/15/2009 1:45:30 PM2009
"yyyyy"The year as a five-digit number. 5/15/2009 1:45:30 PM02009
"z"Hours offset from UTC, with no leading zeros. 5/15/2014 1:45:30 PM -07:00-7
"zz"Hours offset from UTC, with a leading zero for a single-digit value. 5/15/2014 1:45:30 PM -07:00-07
"zzz"Hours and minutes offset from UTC. 5/15/2014 1:45:30 PM -07:00-07:00
"st"Date ordinal (st, nd, rd and th) display from day of the date. 5/15/2014 1:45:30 PM15th

Using the code

var dayNames = ['Sun', 'Mon', 'Tues', 'Wednes', 'Thurs', 'Fri', 'Satur'];
var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
Date.prototype.format = function (format) {
    var wordSplitter = /\W+/, _date = this;
    this.Date = function (format) {
        var words = format.split(wordSplitter);
        words.forEach(function(w) {
            if (typeof(wordReplacer[w]) === "function") {
                format = format.replace(w, wordReplacer[w]() );
            }
            else {
                wordReplacer['e'](w);
            }
        });
        return format.replace(/\s+(?=\b(?:st|nd|rd|th)\b)/g, "");
    };
    var wordReplacer = {
        //The day of the month, from 1 through 31. (eg. 5/1/2014 1:45:30 PM, Output: 1)
        d : function() {
            return _date.getDate();
        },
        //The day of the month, from 01 through 31. (eg. 5/1/2014 1:45:30 PM, Output: 01)
        dd : function() {
            return _pad(_date.getDate(),2);
        },
        //The abbreviated name of the day of the week. (eg. 5/15/2014 1:45:30 PM, Output: Mon)
        ddd : function() {
            return dayNames[_date.getDay()].slice(0,3);
        },
        //The full name of the day of the week. (eg. 5/15/2014 1:45:30 PM, Output: Monday)
        dddd : function() {
            return dayNames[_date.getDay()] + 'day';
        },
        //The tenths of a second in a date and time value. (eg. 5/15/2014 13:45:30.617, Output: 6)
        f : function() {
            return parseInt(_date.getMilliseconds() / 100) ;
        },
        //The hundredths of a second in a date and time value.  (eg. 5/15/2014 13:45:30.617, Output: 61)
        ff : function() {
            return parseInt(_date.getMilliseconds() / 10) ;
        },
        //The milliseconds in a date and time value. (eg. 5/15/2014 13:45:30.617, Output: 617)
        fff : function() {
            return _date.getMilliseconds() ;
        },
        //If non-zero, The tenths of a second in a date and time value. (eg. 5/15/2014 13:45:30.617, Output: 6)
        F : function() {
            return (_date.getMilliseconds() / 100 > 0) ? parseInt(_date.getMilliseconds() / 100) : '' ;
        },
        //If non-zero, The hundredths of a second in a date and time value.  (eg. 5/15/2014 13:45:30.617, Output: 61)
        FF : function() {
            return (_date.getMilliseconds() / 10 > 0) ? parseInt(_date.getMilliseconds() / 10) : '' ;
        },
        //If non-zero, The milliseconds in a date and time value. (eg. 5/15/2014 13:45:30.617, Output: 617)
        FFF : function() {
            return (_date.getMilliseconds() > 0) ? _date.getMilliseconds() : '' ;
        },
        //The hour, using a 12-hour clock from 1 to 12. (eg. 5/15/2014 1:45:30 AM, Output: 1)
        h : function() {
            return _date.getHours() % 12 || 12;
        },
        //The hour, using a 12-hour clock from 01 to 12. (eg. 5/15/2014 1:45:30 AM, Output: 01)
        hh : function() {
            return _pad(_date.getHours() % 12 || 12, 2);
        },
        //The hour, using a 24-hour clock from 0 to 23. (eg. 5/15/2014 1:45:30 AM, Output: 1)
        H : function() {
            return _date.getHours();
        },
        //The hour, using a 24-hour clock from 00 to 23. (eg. 5/15/2014 1:45:30 AM, Output: 01)
        HH : function() {
            return _pad(_date.getHours(),2);
        },
        //The minute, from 0 through 59. (eg. 5/15/2014 1:09:30 AM, Output: 9
        m : function() {
             return _date.getMinutes()();
        },
        //The minute, from 00 through 59. (eg. 5/15/2014 1:09:30 AM, Output: 09
        mm : function() {
            return _pad(_date.getMinutes(),2);
        },
        //The month, from 1 through 12. (eg. 5/15/2014 1:45:30 PM, Output: 6
        M : function() {
            return _date.getMonth() + 1;
        },
        //The month, from 01 through 12. (eg. 5/15/2014 1:45:30 PM, Output: 06
        MM : function() {
            return _pad(_date.getMonth() + 1,2);
        },
        //The abbreviated name of the month. (eg. 5/15/2014 1:45:30 PM, Output: Jun
        MMM : function() {
            return monthNames[_date.getMonth()].slice(0, 3);
        },
        //The full name of the month. (eg. 5/15/2014 1:45:30 PM, Output: June)
        MMMM : function() {
            return monthNames[_date.getMonth()];
        },
        //The second, from 0 through 59. (eg. 5/15/2014 1:45:09 PM, Output: 9)
        s : function() {
            return _date.getSeconds();
        },
        //The second, from 00 through 59. (eg. 5/15/2014 1:45:09 PM, Output: 09)
        ss : function() {
            return _pad(_date.getSeconds(),2);
        },
        //The first character of the AM/PM designator. (eg. 5/15/2014 1:45:30 PM, Output: P)
        t : function() {
            return _date.getHours() >= 12 ? 'P' : 'A';
        },
        //The AM/PM designator. (eg. 5/15/2014 1:45:30 PM, Output: PM)
        tt : function() {
            return _date.getHours() >= 12 ? 'PM' : 'AM';
        },
        //The year, from 0 to 99. (eg. 5/15/2014 1:45:30 PM, Output: 9)
        y : function() {
            return Number(_date.getFullYear().toString().substr(2,2));
        },
        //The year, from 00 to 99. (eg. 5/15/2014 1:45:30 PM, Output: 09)
        yy : function() {
            return _pad(_date.getFullYear().toString().substr(2,2),2);
        },
        //The year, with a minimum of three digits. (eg. 5/15/2014 1:45:30 PM, Output: 2009)
        yyy : function() {
            var _y = Number(_date.getFullYear().toString().substr(1,2));
            return _y > 100 ? _y : _date.getFullYear();
        },
        //The year as a four-digit number. (eg. 5/15/2014 1:45:30 PM, Output: 2009)
        yyyy : function() {
            return _date.getFullYear();
        },
        //The year as a five-digit number. (eg. 5/15/2014 1:45:30 PM, Output: 02009)
        yyyyy : function() {
            return _pad(_date.getFullYear(),5);
        },
        //Hours offset from UTC, with no leading zeros. (eg. 5/15/2014 1:45:30 PM -07:00, Output: -7)
        z : function() {
            return parseInt(_date.getTimezoneOffset() / 60) ; //hourse
        },
        //Hours offset from UTC, with a leading zero for a single-digit value. (eg. 5/15/2014 1:45:30 PM -07:00, Output: -07)
        zz : function() {
            var _h =  parseInt(_date.getTimezoneOffset() / 60); //hourse
            if(_h < 0) _h =  '-' + _pad(Math.abs(_h),2);
            return _h;
        },
        //Hours and minutes offset from UTC. (eg. 5/15/2014 1:45:30 PM -07:00, Output: -07:00)
        zzz : function() {
            var _h =  parseInt(_date.getTimezoneOffset() / 60); //hourse
            var _m = _date.getTimezoneOffset() - (60 * _h);
            var _hm = _pad(_h,2) +':' + _pad(Math.abs(_m),2);
            if(_h < 0) _hm =  '-' + _pad(Math.abs(_h),2) +':' + _pad(Math.abs(_m),2);
            return _hm;
        },
        //Date ordinal display from day of the date. (eg. 5/15/2014 1:45:30 PM, Output: 15th)
        st: function () {
            var _day = wordReplacer.d();
            return _day < 4 | _day > 20 && ['st', 'nd', 'rd'][_day % 10 - 1] || 'th';
        },
        e: function (method) {
            throw 'ERROR: Not supported method [' + method + ']';
        }
    };
    _pad = function (n, c) {
        if ((n = n + '').length < c) {
            return new Array((++c) - n.length).join('0') + n;
        }
        return n;
    }
    return this.Date(format);
} 

In this section i will show you how to use Date() object with custom formatting.

The "dd" Custom Format

The "dd" custom format string represents the day of the month as a number from 01 through 31.

A single-digit day is formatted with a leading zero. The following example includes the "dd" custom format specifier in a custom format string.

date = new Date();
console.log(date.format('dd st-MMM-yyyy'));  //Output: "15th-May-2014"

The "dddd" Custom Format

The "dddd" custom format string represents the full name of the day of the week.

A day name of the day of week. The following example includes the "dddd" custom format specifier in a custom format string.

date = new Date();
console.log(date.format('dddd, dd/M/yy'));  //Output: "Thursday, 15/5/14" 

The "ff" Custom Format

The "ff" custom format specifier represents the two most significant digits of the seconds fraction; that is, it represents the hundredths of a second in a date and time value.

Following example includes the "ff" custom format specifier in a custom format string.

date = new Date();
console.log(date.format('dddd, dd/M/yy hh:mm:ss.ff'));  //Output: "Thursday, 15/5/14 04:51:28.49"  

The "HH" Custom Format

The "HH" custom format specifier (plus any number of additional "H" specifiers) represents the hour as a number from 00 through 23; that is, the hour is represented by a zero-based 24-hour clock that counts the hours since midnight. A single-digit hour is formatted with a leading zero.

The following example includes the "HH" custom format specifier in a custom format string.

date = new Date();
console.log(date.format('HH:mm:ss'));  //Output: "16:54:51"

The "tt" Custom Format

The "t" custom format specifier represents the first character of the AM/PM designator.

Following example includes the "tt" custom format specifier in a custom format string.

date = new Date();
console.log(date.format('dd-MM-y HH:mm:ss tt'));  //Output: "15-05-14 17:00:20 PM"

The "st" Custom Format

The "st" custom format string represents the ay ordinal of the day (eg. st, nd, rd and th).

Following example includes the "st" custom format specifier in a custom format string.

date = new Date();
console.log(date.format('ddd, dd st-MMM-yyyy HH:mm:ss tt zz'));  //Output: "Thu, 15th-May-2014 17:06:37 PM -05"
 

Points of Interest

Using the above date and time format utility you can generate more than thousands of various formatting string as you like or requirements.

Please fill free to ask me if you would require any help for the same.

Your valuable feedback, comment, suggestion are highly appreciated.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Sunasara Imdadhusen
Software Developer (Senior) Infostretch Ahmedabad-Gujarat
India India
Aspiring for a challenging carrier wherein I can learn, grow, expand and share my existing knowledge in meaningful and coherent way.

sunaSaRa Imdadhusen

AWARDS:
  1. 2nd Best Mobile Article of January 2015
  2. 3rd Best Web Dev Article of May 2014
  3. 2nd Best Asp.Net article of MAY 2011
  4. 1st Best Asp.Net article of SEP 2010

Read More Articles...
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
QuestionMy 5 for you Pin
maninder_singh_wadhva17-Jun-14 23:15
membermaninder_singh_wadhva17-Jun-14 23:15 
AnswerRe: My 5 for you Pin
Sunasara Imdadhusen17-Jun-14 23:23
professionalSunasara Imdadhusen17-Jun-14 23:23 
AnswerRe: My 5 for you Pin
Sunasara Imdadhusen17-Jun-14 23:24
professionalSunasara Imdadhusen17-Jun-14 23:24 
GeneralMy vote of 5 Pin
Mubin M. Shaikh16-Jun-14 20:47
memberMubin M. Shaikh16-Jun-14 20:47 
GeneralRe: My vote of 5 Pin
Sunasara Imdadhusen16-Jun-14 21:17
professionalSunasara Imdadhusen16-Jun-14 21:17 
GeneralMy Vote 5 Pin
kunal_shrimali200412-Jun-14 1:44
memberkunal_shrimali200412-Jun-14 1:44 
GeneralRe: My Vote 5 Pin
Sunasara Imdadhusen12-Jun-14 1:58
professionalSunasara Imdadhusen12-Jun-14 1:58 
QuestionGood work Pin
NIRMAL UPADHYAY12-Jun-14 0:42
memberNIRMAL UPADHYAY12-Jun-14 0:42 
AnswerRe: Good work Pin
Sunasara Imdadhusen12-Jun-14 0:44
professionalSunasara Imdadhusen12-Jun-14 0:44 
GeneralMy vote of 5 Pin
Abidali Suthar10-Jun-14 19:00
memberAbidali Suthar10-Jun-14 19:00 
GeneralRe: My vote of 5 Pin
Sunasara Imdadhusen10-Jun-14 19:56
professionalSunasara Imdadhusen10-Jun-14 19:56 
QuestionNice one Pin
NIRMAL UPADHYAY9-Jun-14 1:28
memberNIRMAL UPADHYAY9-Jun-14 1:28 
AnswerRe: Nice one Pin
Sunasara Imdadhusen9-Jun-14 2:33
professionalSunasara Imdadhusen9-Jun-14 2:33 
QuestionAwesome Work Pin
Rajan Garg20-May-14 2:40
memberRajan Garg20-May-14 2:40 
AnswerRe: Awesome Work Pin
Sunasara Imdadhusen20-May-14 2:42
professionalSunasara Imdadhusen20-May-14 2:42 
GeneralMy vote of 5 Pin
Ajit Yagnesh19-May-14 2:13
memberAjit Yagnesh19-May-14 2:13 
GeneralRe: My vote of 5 Pin
Sunasara Imdadhusen19-May-14 2:15
professionalSunasara Imdadhusen19-May-14 2:15 
QuestionHave you considered 'moment.js' ? Pin
Grant Drury-Green15-May-14 21:18
memberGrant Drury-Green15-May-14 21:18 
AnswerRe: Have you considered 'moment.js' ? Pin
Sunasara Imdadhusen15-May-14 21:21
professionalSunasara Imdadhusen15-May-14 21:21 
GeneralGreat Work Pin
Jagbir Saini15-May-14 5:13
professionalJagbir Saini15-May-14 5:13 
GeneralRe: Great Work Pin
Sunasara Imdadhusen15-May-14 19:32
professionalSunasara Imdadhusen15-May-14 19:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150520.1 | Last Updated 20 May 2014
Article Copyright 2014 by Sunasara Imdadhusen
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid