【问题标题】:Use Date as local, not UTC when using it from bootstrap date picker [duplicate]从引导日期选择器使用日期时,将日期用作本地,而不是 UTC [重复]
【发布时间】:2020-09-18 05:31:24
【问题描述】:

我需要从角度反应形式中获取日期。然后我需要使用日期,对其进行字符串化并将其存储在会话存储中。我希望日期的格式不包含时间戳,而只包含日期(因此 - mm/dd/yyyy 或 dd/mm/yyyy 或任何其他格式)。 我不希望将其用作 UTC 时间 - 只需将其用作本地时间。我继续以 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;
        }
    });
}

用户服务:

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

【问题讨论】:

  • 有本地日期和UTC,没有“全球”日期。日期通常保留为 UTC,除了演示,为了方便用户,它们可能会转换为本地。

标签: javascript json date momentjs to-json


【解决方案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)

【讨论】:

猜你喜欢
  • 2016-02-25
  • 1970-01-01
  • 1970-01-01
  • 2016-09-24
  • 2016-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多