Reputation: 668
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
Upvotes: 0
Views: 6476
Reputation: 175
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.
Upvotes: 0
Reputation: 804
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
And so on...
Upvotes: 1