How to convert date to string format in javascript

In this tutorial, you’ll learn how to format date in JavaScript. Working with date is a common scenario when creating web applications.

You can get the current date and time in JavaScript using the Date object.

// the following gives the current date and time object
new Date[]

Using the date object you can print the current date and time.

let current_datetime = new Date[]
console.log[current_datetime.toString[]]

The above code outputs the current date and time as shown:

// output
"Fri Oct 19 2018 17:10:12 GMT+0530 [IST]"

JavaScript Date Time Format

The above shown date time is the default format. It’s not so straight to change JavaScript date time format.

Change Date Format dd-mmm-yyyy

To convert date to format dd-mmm-yyyy you need to extract the date, month and year from the date object.

let current_datetime = new Date[]
let formatted_date = current_datetime.getDate[] + "-" + [current_datetime.getMonth[] + 1] + "-" + current_datetime.getFullYear[]
console.log[formatted_date]

The above code returns the date in the following format:

To convert the numeric month to string month you can create a month array and query it based on the month index.

const months = ["JAN", "FEB", "MAR","APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
let current_datetime = new Date[]
let formatted_date = current_datetime.getDate[] + "-" + months[current_datetime.getMonth[]] + "-" + current_datetime.getFullYear[]
console.log[formatted_date]

The above code outputs the following format :

// code output
"19-OCT-2018"

Change Date Format yyyy-mm-dd

Converting the date to yyyy-mm-dd format is also similar, but you don’t need the months array.

let current_datetime = new Date[]
let formatted_date = current_datetime.getFullYear[] + "-" + [current_datetime.getMonth[] + 1] + "-" + current_datetime.getDate[]
console.log[formatted_date]

Change Date Format yyyy-mm-dd hh:mm:ss

Similarly you can convert the date to yyyy-mm-dd hh:mm:ss.

let current_datetime = new Date[]
let formatted_date = current_datetime.getFullYear[] + "-" + [current_datetime.getMonth[] + 1] + "-" + current_datetime.getDate[] + " " + current_datetime.getHours[] + ":" + current_datetime.getMinutes[] + ":" + current_datetime.getSeconds[] 
console.log[formatted_date]

The above outputs the following date format :

// output
"2018-10-19 17:25:56"

With the above method you don’t need to use any other jQuery plugin for date time format change in JavaScript.

Adding Leading Zeroes In DateTime

Though the above described method works fine for scenarios where the hour, minute or seconds is greater than 9 but fails for cases where it is less. For example, 03:05:01 will be displayed as 3:5:1 which is not the correct format. So how do you fix ?

You’ll need to add a custom method to append leading zeroes in DateTime.

function appendLeadingZeroes[n]{
  if[n 

Bài mới nhất

Chủ Đề