0

I am looking for a JavaScript ES7 Method, which will convert new Date() into the following format below. Is there an ES7 method which will do this, or else I can manually parse/find/replace myself.

2020-06-30 07.49.28

Date with hyphen, time with period.

Currently using typescript in Angular 8, however JavaScript syntax will also work.

Also open to Angular Method, Moment, Lodash or other library method.

*If none available, will take simplest find/replace/regex method,

hanan
  • 1,245
  • 8
  • 17
  • a variation on https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date – BryanOfEarth Jul 07 '20 at 22:08
  • hi @BryanOfEarth saw that already, question does not fully account for time functions, kind of general –  Jul 07 '20 at 22:13

3 Answers3

4

If u want to display in html then use datepipe

<h1>{{date |date:'yyyy-MM-dd hh.mm ss'  }}</h1>

Typescript:

let newDateFormat = (new DatePipe('en-US').transform(new Date(), 'MM-dd-yyyy hh.mm.ss'));

if u want format date for other things like assigning to file Name, then use ngx-moment and make ur life easy u can format ur date like this

moment().format('YYYY-MM-DD HH.mm.ss');
hanan
  • 1,245
  • 8
  • 17
  • ok, I also need to store as Typescript variable, in console log, this will work also –  Jul 07 '20 at 22:19
  • 1
    its a bad idea to store date in variable as string. bcs when ever u have to use it in any computation u have to parse it to date. its better to use https://www.npmjs.com/package/ngx-moment it better then native date. – hanan Jul 07 '20 at 22:23
  • yep, placed in your answer suggestion queue –  Jul 07 '20 at 22:57
0

You mention momentJS, that library makes formatting dates very straightforward with a .format() method:

moment().format('YYYY-MM-DD HH.mm.ss');

Note: new Date() is implicit when you invoke moment() without an argument.

zcoop98
  • 1,604
  • 1
  • 10
  • 18
0

Here is some code, i am sure you can improve it

var d = new Date("06/30/2020 07:49:28");
var date = [
  d.getFullYear(),
  ('0' + (d.getMonth() + 1)).slice(-2),
  ('0' + d.getDate()).slice(-2),
 
].join('-');
console.log("date: ",date);

var time=[
 ('0' + d.getHours()) .slice(-2),
  ('0' + d.getMinutes()).slice(-2),
    ('0' + d.getSeconds()).slice(-2),

].join('.');
console.log("time: ",time);
console.log("result: ",date+" "+time);
Nonik
  • 612
  • 3
  • 9