当从bootstrap date picker中使用Date时,使用本地的Date,而不是UTC [replicate] 。

问题描述 投票:0回答:1

我需要从一个angular reactive form中获取日期。然后我需要使用日期。将其字符串化并存储在会话存储中。. 我希望日期的格式为 不含时间戳但只有日期(因此--mmddyyyy或ddmmyyyy,或任何其他格式)。. 我一直在获取UTC中的日期--所以如果我是UTC+2,我得到的日期转换为前一天小时22:00.使用它作为字符串是一种方式做,但我想有它作为日期。JSON.stringify 不会使用UTC约定并将其作为本地日期处理 - 将其设置为字符串而不是日期对象?

请看我的代码: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()">    

组件。

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;
}

在userDetailsData(模型)中。

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;
    }
  }
}  
javascript angular date momentjs utc
1个回答
1
投票

的JavaScript Date 对象以UTC存储日期。

如果你想用当地时区的日期,你可以输出函数 Date 对象的时区。例如,要获取当地时区的当前日期。

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)
© www.soinside.com 2019 - 2024. All rights reserved.