Skip to main content

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

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 stringcan 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.
FormatDescriptionDate ExampleOutput
"d"The day of the month, from 1 through 31.5/1/2014 1:45:30 PM1
"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 value5/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.  
        //(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.
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.
The 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.
The 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).
The 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 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.


Ref: https://www.codeproject.com/Articles/773356/Date-and-Time-Formatting-in-JavaScript-like-NET-Cs

Comments

  1. I really loved reading your blog. It was very well authored and easy to undertand. Unlike additional blogs I have read which are really not tht good. I also found your posts very interesting. In fact after reading, I had to go show it to my friend and he ejoyed it as well! http://psiprograms.com

    ReplyDelete

Post a Comment

Popular posts from this blog

C# Generic class to parse value - "GenericConverter"

    public class GenericConverter     {         public static T Parse<T>(string sourceValue) where T : IConvertible         {             return (T)Convert.ChangeType(sourceValue, typeof(T));         }         public static T Parse<T>(string sourceValue, IFormatProvider provider) where T : IConvertible         {             return (T)Convert.ChangeType(sourceValue, typeof(T), provider);         }     }     public static class TConverter     {         public static T ChangeType<T>(object value)         {             return (T)ChangeType(typeof(T), value);         }         public static object ChangeType(Type t, object value)         {             TypeConverter tc = TypeDescriptor.GetConverter(t);             return tc.ConvertFrom(value);         }         public static void RegisterTypeConverter<T, TC>() where TC : TypeConverter         {             TypeDescriptor.AddAttributes(typeof(T), new TypeConverterAttribute(typeof(TC)));         }     } ----------------

How to create a countdown timer in jquery

Create a countdown timer in jQuery First we need to include the jQuery library file to the HTML page to perform this task. To do that we need to understand that what exactly a jQuery library fie is ? JQuery library file is the library of JavaScript, which means this file contains the predefined functions of jQuery. We just need to call these functions to perform the task. jQuery functions reduces the lines of code and makes our task easy. As this jQuery library file contains the javascript functions so we need to call the function within <script> </script> tag. Now after including the file, we need to define a variable which will store that for how long you want the timer on the page(c=60) and now the time you set needs to be changed in hours , minutes and seconds using the code “ var hours = parseInt( time / 3600 ) % ;var minutes = parseInt( time / 60 ) % 60; var seconds = time % 60;” Now we need to put the condition if timer got finished (if (t

Tip/Trick: Fix Common SEO Problems Using the URL Rewrite Extension

Search engine optimization (SEO) is important for any publically facing web-site.  A large % of traffic to sites now comes directly from search engines, and improving your site’s search relevancy will lead to more users visiting your site from search engine queries.  This can directly or indirectly increase the money you make through your site. This blog post covers how you can use the free Microsoft  URL Rewrite Extension  to fix a bunch of common SEO problems that your site might have.  It takes less than 15 minutes (and no code changes) to apply 4 simple  URL Rewrite  rules to your site, and in doing so cause search engines to drive more visitors and traffic to your site.  The techniques below work equally well with both ASP.NET Web Forms and ASP.NET MVC based sites.  They also works with all versions of ASP.NET (and even work with non-ASP.NET content). [In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at:  twitter.com/scottg