Home > Software design >  How to format JSON dates with JavaScript?
How to format JSON dates with JavaScript?

Time:11-01

I have an HTML <input type="date" name="departing" /> which returns for example the date in the following format: 2021-11-07

When I forward this variable to my handlebars, it is being displayed as follows:

Mon Nov 08 2021 01:00:00 GMT 0100 (Central European Standard Time)

I would like to have it displayed as:

07/11/2021

I tried formatting it with date-fns like this:

departing = format(parseISO(departing.getDate()), "dd/MM/yyyy");

But then my handlebar shows: "Invalid Date"

I am so confused. Any ideas on how to get that date to be displayed in the 07/11/2021 format?

CodePudding user response:

First of all create a date object

const newDate = new Date();

Now you can manipulate code to get answer whatever you want

var outputDate = newDate .getDate()   "/"    (newDate.getMonth() 1)   "/"   
newDate.getFullYear();

Output will be looks like 01/11/2021

CodePudding user response:

Well you could go as simple as using #getDate(), #getMonth() and #getFullYear() methods separately then displaying them in the order you'd like like so:

const date = new Date(departing);
const day = date.getDate();
const month = date.getMonth()   1;
const year = date.getFullYear();

console.log(`${day}/${month}/${year}`);

Hope it answers the question.

CodePudding user response:

You could do it by several ways

method 1:-

let n = new Date()
console.log(n.toLocaleDateString("en-US")
output=== 31/9/2021

method 2 :- get separate values and merge

let n = new Date()
console.log(n.getDate() "/" n.getMonth() "/" n.getFullYear())
output=== 31/9/2021
  • Related