In Javascript I have Date object which I need to convert to string of format dd.mm.yyyy and dd.mm.yyyy hh24:mi:ss. How do I format the Date in Javascript?

3 Answers

3
Robby Cornelissen On

Looks like a German locale format, so you can use Date.toLocaleDateString() and Date.toLocaleTimeString() with a German locale setting (de-DE):

const date = new Date();

const dateString = date.toLocaleDateString('de-DE');
const timeString = date.toLocaleTimeString('de-DE');

const string = `${dateString} ${timeString}`;

console.log(string);

1
Hien Nguyen On

You can use momentjs library for your requirement.

constructor(  ) { 
  let now = moment().format("YYYY-MM-DD HH:mm:ss");
  let now2 = moment().format("DD.MM.YYYY");
     this.format1 = now;
     this.format2 = now2;
     console.log(now);

    this.date = moment(this.format1, "YYYY-MM-DD HH:mm:ss");

  }

https://stackblitz.com/edit/momentjs-format-date?file=app/app.component.ts

0
alvarofvr On

You can use methods of Date object for build your date string:

const now = new Date();

const formattedDate = now.getDate() + "." + ('0' + (now.getMonth()+1)).slice(-2) + "." + now.getFullYear();

const formattedDateTime = formattedDate + " " + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();

console.log(formattedDate); // 28.05.2019

console.log(formattedDateTime); // 28.05.2019 13:19:43