Click here to Skip to main content
15,885,069 members
Articles / Web Development / HTML

Date and Time Formatting in JavaScript like .NET C# or VB.NET

Rate me:
Please Sign up or sign in to vote.
4.81/5 (24 votes)
19 May 2014CPOL5 min read 50.2K   350   36   23
Custom Date and Time formatting in JavaScript like in .NET C# or VB.NET

Introduction

A date and time format string defines the text representation of a Date() object, that results in 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 requires that an input string conforms exactly to a particular pattern for the parse operation to succeed, otherwise it will give 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.

Format Description Date Example Output
"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 PM 01
"ddd" The abbreviated name of the day of the week. 5/15/2014 1:45:30 PM Thu
"dddd" The full name of the day of the week. 5/15/2014 1:45:30 PM Thursday
"f" The tenths of a second in a date and time value. 5/15/2014 13:45:30.617 6
"ff" The hundredths of a second in a date and time value 5/15/2014 13:45:30.617 61
"fff" The milliseconds in a date and time value. 5/15/2014 13:45:30.617 617
"F" If non-zero, the tenths of a second in a date and time value. 5/15/2014 13:45:30.617 6
"FF" If non-zero, the hundredths of a second in a date and time value. 5/15/2014 13:45:30.617 61
"FFF" If non-zero, the milliseconds in a date and time value. 5/15/2014 13:45:30.617 617
"h" The hour, using a 12-hour clock from 1 to 12. 5/15/2014 1:45:30 AM 1
"hh" The hour, using a 12-hour clock from 01 to 12. 5/15/2014 1:45:30 AM 01
"H" The hour, using a 24-hour clock from 0 to 23. 5/15/2014 1:45:30 AM 1
"HH" The hour, using a 24-hour clock from 00 to 23. 5/15/2014 1:45:30 AM 01
"m" The minute, from 0 through 59. 5/15/2014 1:09:30 AM 9
"mm" The minute, from 00 through 59. 5/15/2014 1:09:30 AM 09
"M" The month, from 1 through 12. 5/15/2014 1:45:30 PM 6
"MM" The month, from 01 through 12. 5/15/2014 1:45:30 PM 06
"MMM" The abbreviated name of the month. 6/15/2014 1:45:30 PM Jun
"MMMM" The full name of the month. 6/15/2014 1:45:30 PM June
"s" The second, from 0 through 59. 5/15/2014 1:45:09 PM 9
"ss" The second, from 00 through 59. 5/15/2014 1:45:09 PM 09
"t" The first character of the AM/PM designator. 5/15/2014 1:45:09 PM P
"tt" The AM/PM designator. 5/15/2014 1:45:09 PM PM
"y" The year, from 0 to 99. 5/15/2014 1:45:09 PM 9
"yy" The year, from 00 to 99. 5/15/2014 1:45:09 PM 09
"yyy" The year, with a minimum of three digits. 5/15/2009 1:45:30 PM 2009
"yyyy" The year as a four-digit number. 5/15/2009 1:45:30 PM 2009
"yyyyy" The year as a five-digit number. 5/15/2009 1:45:30 PM 02009
"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 PM 15th

Using the Code

JavaScript
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.  
        //(e.g., 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.  
        //(e.g., 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. 
        //(e.g., 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.

JavaScript
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.

JavaScript
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.

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

JavaScript
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.

JavaScript
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.

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

JavaScript
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).

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

JavaScript
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 strings as you like or as per your requirements.

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

Your valuable feedback, comments, suggestions are highly appreciated.

License

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


Written By
Technical Lead 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...

Comments and Discussions

 
GeneralMy vote of 4 Pin
Michael A. Allen4-Jun-20 2:40
Michael A. Allen4-Jun-20 2:40 
BugFound a bit of a logic bug in your code ... Pin
Michael A. Allen3-Jun-20 11:09
Michael A. Allen3-Jun-20 11:09 
QuestionMy 5 for you Pin
maninder_singh_wadhva17-Jun-14 22:15
maninder_singh_wadhva17-Jun-14 22:15 
AnswerRe: My 5 for you Pin
Sunasara Imdadhusen17-Jun-14 22:23
professionalSunasara Imdadhusen17-Jun-14 22:23 
AnswerRe: My 5 for you Pin
Sunasara Imdadhusen17-Jun-14 22:24
professionalSunasara Imdadhusen17-Jun-14 22:24 
GeneralMy vote of 5 Pin
Mubin M. Shaikh16-Jun-14 19:47
professionalMubin M. Shaikh16-Jun-14 19:47 
GeneralRe: My vote of 5 Pin
Sunasara Imdadhusen16-Jun-14 20:17
professionalSunasara Imdadhusen16-Jun-14 20:17 
GeneralMy Vote 5 Pin
kunal_shrimali200412-Jun-14 0:44
kunal_shrimali200412-Jun-14 0:44 
GeneralRe: My Vote 5 Pin
Sunasara Imdadhusen12-Jun-14 0:58
professionalSunasara Imdadhusen12-Jun-14 0:58 
QuestionGood work Pin
NIRMAL UPADHYAY11-Jun-14 23:42
NIRMAL UPADHYAY11-Jun-14 23:42 
AnswerRe: Good work Pin
Sunasara Imdadhusen11-Jun-14 23:44
professionalSunasara Imdadhusen11-Jun-14 23:44 
GeneralMy vote of 5 Pin
Abidali Suthar10-Jun-14 18:00
Abidali Suthar10-Jun-14 18:00 
GeneralRe: My vote of 5 Pin
Sunasara Imdadhusen10-Jun-14 18:56
professionalSunasara Imdadhusen10-Jun-14 18:56 
QuestionNice one Pin
NIRMAL UPADHYAY9-Jun-14 0:28
NIRMAL UPADHYAY9-Jun-14 0:28 
AnswerRe: Nice one Pin
Sunasara Imdadhusen9-Jun-14 1:33
professionalSunasara Imdadhusen9-Jun-14 1:33 
QuestionAwesome Work Pin
Rajan Garg20-May-14 1:40
Rajan Garg20-May-14 1:40 
AnswerRe: Awesome Work Pin
Sunasara Imdadhusen20-May-14 1:42
professionalSunasara Imdadhusen20-May-14 1:42 
GeneralMy vote of 5 Pin
Ajit Yagnesh19-May-14 1:13
Ajit Yagnesh19-May-14 1:13 
GeneralRe: My vote of 5 Pin
Sunasara Imdadhusen19-May-14 1:15
professionalSunasara Imdadhusen19-May-14 1:15 
QuestionHave you considered 'moment.js' ? Pin
Grant Drury-Green15-May-14 20:18
Grant Drury-Green15-May-14 20:18 
AnswerRe: Have you considered 'moment.js' ? Pin
Sunasara Imdadhusen15-May-14 20:21
professionalSunasara Imdadhusen15-May-14 20:21 
GeneralGreat Work Pin
Jagbir Saini15-May-14 4:13
professionalJagbir Saini15-May-14 4:13 
GeneralRe: Great Work Pin
Sunasara Imdadhusen15-May-14 18:32
professionalSunasara Imdadhusen15-May-14 18:32 

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

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