Moment.JS is an intelligent JavaScript library to Parse, validate, manipulate, and display dates and times for given formats.

Here in this article, I want to provide some mostly used conversions for any projects which hard to find on the internet. Please visit the official site here to know about how to download and configure this library in your project.

Moment.JS will be mostly used in applications which deal with multi-language support. For example, if our application wants to show the date and time formats based on user preference. We can send this information based on logged in user and convert the dates as needed and then re-convert it to the default date and time format while sending the submitted information to the server such that we can avoid additional overhead of conversions at the server side.

Following are the couple of JavaScript functions, which mostly covers all the scenarios needed for the above requirement. You can tailor these functions as per your need, for example, if you need to send the format string and language at runtime based on user selection on your website or application.

GetPreferredFormatDateString 

 The following JavaScript method can be used to convert any format to preferred date time format based on preferred language. In the given example, we are providing a date string as input in the DD-MMM-YYYY format of English language and expecting the date in DD.MMM.YY in the French language.  

function ToPreferredDateFormatString(dateString) { 

         moment.locale("en"); 
        var newdate = moment(dateString).format("DD-MMM-YYYY"); 

        if (newdate != undefined && newdate != null) { 
            moment.locale("fr"); 
            var newdateLocaleString = moment(newdate).format("DD.MMM.YY"); 

             return newdateLocaleString; 
        } 
        return dateString; 
    }

When we call the following statement 

ToPreferredDateFormatString("12-Jun-2018");

The result will be: “12.juin.18”  (DD.MMM.YY format in the French Language) 

To JavaScript Date Object 

Following is the JavaScript method which can be used to convert any given date string with any format into JavaScript Date object. This is mostly required to do any validations on given dates. 

function ToJSDate(dateString){ 
var jsDateObject = moment(dateString, "MM/DD/YYYY").toDate(); 

return jsDateObject; 
}

When we call the following statement 

ToJSDate("06/12/2018");

The result will be: Tue Jun 12 2018 00:00:00 GMT+0530 (India Standard Time) 

I think I have given less explanation on these methods but I believe these are mostly self-explanatory. If you need more information please don’t hesitate to drop a comment below such that it can help me to update this content with appropriate information.

 

Happy Coding 🙂