I need to get date from an angular reactive form. Then I need to use the date, stringfy it and store it in a session storage. I would like the date to be in a format that not contains time stamp, but only the date (hence - mm/dd/yyyy or dd/mm/yyyy, or any other format). I don't want it to be used as a UTC time - just use it as local. I keep on getting the date in a UTC - so if I'm UTC+2, I get the date converted to be the day before hour 22:00. Using it as string is one way doing it, but I would like to have it as date What is the best way to configure the datepicker\do it so that the JSON.stringify won't use a UTC convention and treat it as local date - setting it as string and not as a date object ?
See my code: HTML:
<mat-form-field>
<mat-label>Date Of Birth</mat-label>
<input matInput [matDatepicker]="picker" formControlName="DateOfBirth">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
<button mat-raised-button type="submit" (click)="saveUserDetails()">
Component:
ngOnInit() {
if (this.userService.userDataInSession && this.userService.userDataInSession.FirstName)
{
let sessionUserData = this.userService.userDataInSession;
this.userDetailsForm = this.fb.group(
{
DateOfBirth:[sessionUserData.DateOfBirth]
}
}
else
{
this.userDetailsForm = this.fb.group(
{
DateOfBirth:['']
}
}
}
saveUserDetails()
{
this.userDetailsData.initByFormControls(this.userDetailsForm.controls);
this.userService.userDataInSession = this.userDetailsData;
}
In userDetailsData (model):
public initByFormControls(formControls : any)
{
Object.keys(this).forEach(key =>
{
if (formControls[key])
{
this[key] = formControls[key].value;
}
});
}
UserServise:
export class UserService
{
get userDataInSession() : UserData
{
if (!sessionStorage.getItem("userData") || sessionStorage.getItem("userData") == "undefined")
{
return new UserData();
}
else
{
return JSON.parse(sessionStorage.getItem("userData"));
}
}
set userDataInSession(value)
{
sessionStorage.setItem("userData", JSON.stringify(value));
}
setUserDataProperty(propertyName : string, value : any)
{
if (this.userDataInSession.hasOwnProperty(propertyName))
{
this.userDataInSession[propertyName] = value;
this.userDataInSession = this.userDataInSession;
}
}
}