Isaac
Isaac

Reputation: 170

How to format the date to (dd/mm/yyyy hh:mm:ss)

How can I convert the date below into this template (dd/mm/yyyy hh:mm:ss) ?

05/04/2021 14:52

I tried to do it that way, but I only get the time and not the date with time.

var data = new Date('05/04/2021 14:52');
var time = data.toLocaleTimeString('pt-PT', {hour12: false});
console.log(time);

Upvotes: 4

Views: 28010

Answers (3)

OLezhko
OLezhko

Reputation: 150

If you need more date-related stuff than simple date formatting, you can use Moment.js.

moment().format('MMMM Do yyyy, h:mm:ss a'); // April 5th 2021, 9:16:13 pm
moment().format('DD/MM/yyyy hh:mm'); // 05/04/2021 21:18

If you need to format your Date object, simply use:

moment(date).format('DD/MM/yyyy hh:mm');

Moment.js is also useful for operation on dates like days, weeks, months adding/subtracting, getting the start of a week, month, quarter, and many other useful operations.

Upvotes: 2

Dai Nguyen
Dai Nguyen

Reputation: 64

This is my solution. If you want to create a advanced format, you can read more about object Intl https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl

const formatDate = new Intl.DateTimeFormat("en" , {
  day: "2-digit",
  month: "2-digit",
  year: "numeric",
  hour: "2-digit",
  minute: "2-digit",
  second: "2-digit",
  hour12: false
});

console.log(formatDate.format(new Date('05/04/2021 14:52')))

Upvotes: 3

Ashish Sharma
Ashish Sharma

Reputation: 476

You can use below script

var data = new Date('05/04/2021 14:52');
console.log(data.toLocaleString('en-GB',{hour12: false}));

Output : "04/05/2021, 14:52:00"

Upvotes: 3

Related Questions