Reputation: 545
i have some trouble properly using date with angular5
i fetch data from a mocked api where date is generated like that : 24/07/2018 00:00:00 so there is no problem with resarch or anything manipulating those dates.
sample of the generation in api mock :
for (int i = 1; i <= NUMBER_OF_POLICIES; i++)
{
Policy lPolicy = new Policy { Id = i, Name = string.Concat("Policy number ", i), Date = DateTime.Now.AddDays(i) };
p.Add(lPolicy);
}
problem comes when i update dates with angular material DatePicker component.
with the picker, date shows up like tis :
Mon Jul 30 2018 00:00:00 GMT+0200
so when i update the item, date is passed like this :
updated item: {"id":1,"name":"Policy number 1","date":"2018-07-29T22:00:00.000Z"}
any idea how to deal with locales ?
EDIT :
Here is the problem when i do some research :
Upvotes: 2
Views: 4133
Reputation: 545
const offset = p.date.getTimezoneOffset();
const test = p.date.setMinutes(p.date.getMinutes() - offset);
console.log(test) returns :
updated item: {"id":1,"name":"Policy number 1","date":"2018-07-31T00:00:00.000Z"}
it works too but, is that "clean"?
Upvotes: 0
Reputation: 7739
You can use DatePipe in the component itself, and format the date using pre-defined-format-options
Try this
import { DatePipe } from '@angular/common';
class Service {
constructor(private datePipe: DatePipe) {}
changeDate(date) {
return this.datePipe.transform(date, 'yyyy-MM-dd');
}
}
Or you can format date like this as well
var formatted = new DatePipe().transform(raw, 'yyyy-MM-dd');
Upvotes: 2
Reputation: 114
use moment for date and time, which gives the necessary formats.
momentjs have different properties to get the time and date in necessary format.
newDate = this.Today
date = moment(this.newDate)
you can also pass necessary formats like
date = moment(this.newDate).format('DD/MM/YYYY')
Upvotes: 1