0

I am having trouble to create a Date only Date Object when using the 'YYYY-MM-DD' input

When i use the following Code to create a new Date object

let date1 = new Date('2022-01-06')
let date2 = new Date('01/06/2022')

I get the following results

date1 = Wed Jan 05 2022 16:00:00 GMT-0800 (Pacific Standard Time)
date2 = Thu Jan 06 2022 00:00:00 GMT-0800 (Pacific Standard Time) 

So its the same Input to create a new Date Object but i get different times. As i am storing my data in a json doc store its in the 2022-01-06 format and i need to get a date object back that has no Time just like Date2

NoSoup4you
  • 640
  • 1
  • 10
  • 34
  • [moment.js](https://momentjs.com) instantiates dates in your timezone. Plus there is a lot of solid integration with Angular. Down side is that it is somewhat extra in package size – bloo Jan 04 '22 at 08:30

2 Answers2

1

You can use this :

let date1 = new Date('2022-01-06').toLocaleDateString("en-US")

it will give you output like this :

'1/6/2022'

and here is another example :

var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
var today  = new Date();

console.log(today.toLocaleDateString("en-US")); // 9/17/2016 console.log(today.toLocaleDateString("en-US", options)); // Saturday, September 17, 2016

I took reference from this answer

And if you want to use any third party library there are so many which can help you with that here I'm attaching one

Example :

var dateFormat = require('dateformat');
var now = new Date();
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");

it will return :

Saturday, June 9th, 2007, 5:46:21 PM

List of third party libraries

  1. Date-fns
  2. Moment
  3. Day JS

And so on...

Manish Patidar
  • 526
  • 4
  • 14
0

You can use DatePipe to convert date in this format 'yyyy-MM-dd'.

import { DatePipe } from '@angular/common'
...
constructor(public datepipe: DatePipe){}
...
public date:Date;
myMethod(){
 this.date=new Date();
 let LatestDate =this.datepipe.transform(this.date, 'yyyy-MM-dd');
}

and just add Datepipe in 'providers' array of app.module.ts.