Click here to Skip to main content
Click here to Skip to main content

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

, 19 May 2014
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. 1st Best Asp.Net article of SEP 2010
  2. 2nd Best Asp.Net article of MAY 2011
 
Read More Articles...
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
QuestionMy 5 for you Pinmembermaninder_singh_wadhva17-Jun-14 22:15 
AnswerRe: My 5 for you PinpremiumSunasara Imdadhusen17-Jun-14 22:23 
AnswerRe: My 5 for you PinpremiumSunasara Imdadhusen17-Jun-14 22:24 
GeneralMy vote of 5 PinpremiumMubin M. Shaikh16-Jun-14 19:47 
GeneralRe: My vote of 5 PinpremiumSunasara Imdadhusen16-Jun-14 20:17 
GeneralMy Vote 5 Pinmemberkunal_shrimali200412-Jun-14 0:44 
GeneralRe: My Vote 5 PinpremiumSunasara Imdadhusen12-Jun-14 0:58 
QuestionGood work PinmemberNIRMAL UPADHYAY11-Jun-14 23:42 
AnswerRe: Good work PinpremiumSunasara Imdadhusen11-Jun-14 23:44 
GeneralMy vote of 5 PinmemberAbidali Suthar10-Jun-14 18:00 
GeneralRe: My vote of 5 PinpremiumSunasara Imdadhusen10-Jun-14 18:56 
QuestionNice one PinmemberNIRMAL UPADHYAY9-Jun-14 0:28 
AnswerRe: Nice one PinpremiumSunasara Imdadhusen9-Jun-14 1:33 
QuestionAwesome Work PinmemberRajan Garg20-May-14 1:40 
AnswerRe: Awesome Work PinpremiumSunasara Imdadhusen20-May-14 1:42 
GeneralMy vote of 5 PinmemberAjit Yagnesh19-May-14 1:13 
GeneralRe: My vote of 5 PinpremiumSunasara Imdadhusen19-May-14 1:15 
QuestionHave you considered 'moment.js' ? PinmemberGrant Drury-Green15-May-14 20:18 
AnswerRe: Have you considered 'moment.js' ? PinpremiumSunasara Imdadhusen15-May-14 20:21 
GeneralGreat Work PinprofessionalJagbir Saini15-May-14 4:13 
GeneralRe: Great Work PinpremiumSunasara Imdadhusen15-May-14 18: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 | Mobile
Web03 | 2.8.140827.1 | Last Updated 20 May 2014
Article Copyright 2014 by Sunasara Imdadhusen
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid