0

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;
    }
  }
}  
Guy E
  • 1,775
  • 2
  • 27
  • 55
  • There are local dates and UTC, there is no "global" date. Dates are typically kept as UTC except for presentation, when they might be converted to local for user friendliness. – RobG May 31 '20 at 00:59

1 Answers1

1

The JavaScript Date object stores dates in UTC.

If you want the date in the local time zone, you output the results of the Date object in that timezone. For example, to get the current date in the local timezone:

let now = new Date();
let nowYear = now.getFullYear();
let nowMonth = now.getMonth() + 1;
let monthStr = ('0'+nowMonth).slice(-2);
let nowDate = now.getDate();
let dateStr = ('0'+nowDate).slice(-2);
let date = monthStr + '/' + dateStr + '/' + nowYear
console.log('date in local timezone:', date)
terrymorse
  • 6,771
  • 1
  • 21
  • 27
  • If you need more complex calculations on date objects you should have a look at moment.js (https://momentjs.com/) – gsa.interactive May 30 '20 at 20:41
  • 1
    There are already many, many [questions on formatting dates](https://stackoverflow.com/search?q=%5Bjavascript%5D+how+to+format+a+date). – RobG May 31 '20 at 00:56