Change Date Time Format in Javascript In Any Desired Format

This blog will show you how to customize date and time through javascript in different formats.

To check any condition, I have used javascript ternary operator instead of IF statement that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is true followed by a colon ( : ), and finally the expression to execute if the condition is false.

To Get Different Javascript Date Format(like dd/mm/yyyy or yyyy-mm-dd and so on) From Current Date

Just edit line number 13 in the below code and get any JS date format.

To Extract Time From Current Date Time and Format As hh:mm:ss

To Get Date and Time Both

Customize date format using Moment Js

If you want to customize the current date format then it is very easy with the moment.js. You need to download and import the moment.js and then use the predefined functions provided by the package.

To customize current date use below

To add or subtract days from current date use below

You can also read how to do subtract and add operation on date

Customize date format using toLocaleDateString(locales)

We can use different timezones to get the different date formates using toLocaleDateString().

For example if we need YYYY-MM-DD format then we can use “en-CA”.

Below is the list of other options you can use

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *