How to change Date Format in Javascript ?

 


Date and time are the most integral part of our application as they play a important role in our everyday life. We can't imagine our life without Date and Time and therefore we can't make an application without them

There is a need to play with the date format as well and sometimes client can be specific about the format as well. I seriously had clients that wanted to display "May" in some other language and that was different from normal convention as well.

The method that we are discussing here can be useful to change the Date Format easily. It's easy to do the same without the need of any external library like moment.js.

Suppose we have date "03-04-2020" and we need to convert it to "March 04, 2020".
For this, First, we need to get the date object. You can get this with the help of new Date("03-04-2020")

Once you get the Date Object you can get the date, month, and year from the date object.
After getting the individual elements of date you can proceed in the way demonstrated in the below example with the help of replacing and simple array methodologies.

So lets, skip the talking and move to the code part. 

STOP TALKING AND SHOW ME THE CODE

.

function converToDateFormat(dateToConvert,dateFormat){
    let _convertedDate;

    //Get Date Object
    let _getDateObject = new Date(dateToConvert)

    //Get Individual Date Elements
    let _dateValue = _getDateObject.getDate();
    let _monthValue = _getDateObject.getMonth();
    let _yearValue = _getDateObject.getFullYear();

    _dateValue= (_dateValue.toString().length==1?"0"+_dateValue:_dateValue);
    _monthValue = (_monthValue.toString().length==1?"0"+_monthValue:_monthValue);

    //Replace Months
    var _occurenceOfM=((dateFormat.split("m")).length - 1);
    if(_occurenceOfM==2){
       _convertedDate = dateFormat.replace("mm",_monthValue);
    } else{
       //You can change this for different language as per your need.
       let _monthArr = ["Jan","Feb","Mar","April","May","June","July","Aug","Sept","Oct","Nov","Dec"];
       _convertedDate = dateFormat.replace("mmm",_monthArr[parseInt(_monthValue)- 1]);
   }
    //Replace Date
    _convertedDate = _convertedDate.replace("dd",_dateValue);
    //Replace Year
    _convertedDate = _convertedDate.replace("yyyy",_yearValue).replace("yy",_yearValue.toString().substring(2,4));
    return _convertedDate;

}

/* This can be further modified according to needs like the month array can be modified as you need, the occurrence of single m can be handled as well if you don't want to show 0 in front of numbers less than 10 and many more.*/



The method can be used when we have more customization for the date format. 

There are conventional methods as well that can be used according to the locale. 

Let's also discuss these when we are talking about the Date Format.



1.  Using Intl.DateTimeFormat to format the date.

Recently, the Javascript team introduced Intl.DateTimeFormat object that enables us to format language-sensitive date and time.


Example using basic Intl.DateTimeFormat -


var date = new Date(2016, 11, 20, 3, 0, 0);

// the default locale, and the default time zone
console.log(new Intl.DateTimeFormat().format(date));
// → "11/20/2016" if run with en-US locale (language) and time zone America/Los_Angeles (UTC-0800)


One very useful use case of Intl.DateTimeFormat is that it can be used when our application is made for different countries and we want to convert the date according to a different locale.

Example Using Locale -


var date = new Date(Date.UTC(2020, 02, 20, 3, 0, 0));

// Results below use the time zone of America/Los_Angeles (UTC-0800, Pacific Standard Time)

// US English uses month-day-year order
console.log(new Intl.DateTimeFormat('en-US').format(date));
// → "3/20/2020"

// British English uses day-month-year order
console.log(new Intl.DateTimeFormat('en-GB').format(date));
// → "20/03/2020"

// Korean uses year-month-day order
console.log(new Intl.DateTimeFormat('ko-KR').format(date));
// → "2020. 3. 20."

// Arabic in most Arabic speaking countries uses real Arabic digits
console.log(new Intl.DateTimeFormat('ar-EG').format(date));
// → "٢٠‏/٣‏/٢٠٢٠"

// for Japanese, applications may want to use the Japanese calendar,
// where 2012 was the year 24 of the Heisei era
console.log(new Intl.DateTimeFormat('ja-JP-u-ca-japanese').format(date));
// → "R2/3/20"

// when requesting a language that may not be supported, such as
// Balinese, include a fallback language, in this case Indonesian

console.log(new Intl.DateTimeFormat(['ban', 'id']).format(date));
// → "20/3/2020"



Intl.DateTimeFormat also supports many options that can be used for further modification/ customization. This is very useful when we want Weekday along with the date and the weekday should come in the specified locale. It can also be when we want to display the month (long) according to locale and many such cases.

Example Using Different Options -



var date = new Date(Date.UTC(2020, 02, 20, 3, 0, 0, 200));

// request a weekday along with a long date
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
console.log(new Intl.DateTimeFormat('de-DE', options).format(date));
// → "Donnerstag, 20. Dezember 2012"

// an application may want to use UTC and make that visible
options.timeZone = 'UTC';
options.timeZoneName = 'short';
console.log(new Intl.DateTimeFormat('en-US', options).format(date));
// → "Thursday, December 20, 2012, GMT"

// sometimes you want to be more precise
options = {
hour: 'numeric', minute: 'numeric', second: 'numeric',
timeZone: 'Australia/Sydney',
timeZoneName: 'short'
};
console.log(new Intl.DateTimeFormat('en-AU', options).format(date));
// → "2:00:00 pm AEDT"

// sometimes you want to be very precise
options.fractionalSecondDigits = 3;
console.log(new Intl.DateTimeFormat('en-AU', options).format(date));
// → "2:00:00.200 pm AEDT"


// sometimes even the US needs 24-hour time
options = {
year: 'numeric', month: 'numeric', day: 'numeric',
hour: 'numeric', minute: 'numeric', second: 'numeric',
hour12: false,
timeZone: 'America/Los_Angeles'
};
console.log(new Intl.DateTimeFormat('en-US', options).format(date));
// → "12/19/2012, 19:00:00"


// to specify options but use the browser's default locale, use 'default'
console.log(new Intl.DateTimeFormat('default', options).format(date));
// → "12/19/2012, 19:00:00"


2. Using Date.toLocaleString() to format the date.

Similar to 
Intl.DateTimeFormat, Date.toLocaleString helps us to format language-sensitive date and time. Recently, locale and options were introduced in Date.toLocaleString() The new locale and options arguments let applications specify the language whose formatting conventions should be used and allow them to customize the behavior.

Example - 


const event = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));

const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };

console.log(event.toLocaleDateString('de-DE', options));
// expected output: Donnerstag, 20. Dezember 2012

console.log(event.toLocaleDateString('ar-EG', options));
// expected output: الخميس، ٢٠ ديسمبر، ٢٠١٢

console.log(event.toLocaleDateString(undefined, options));
// expected output: Thursday, December 20, 2012 (varies according to default locale)



Note (Performance)
When formatting large numbers of dates, it is better to create an Intl.DateTimeFormat object and use the function provided by its format property.

Thanks for reading, please feel free to contact. 

Post a Comment

0 Comments