打字稿将对象的date属性转换为New Date()

时间:2020-09-21 00:32:14

标签: typescript date

我有一个CurrentWeather模型,该模型是从localStorage解析到对象的。

export interface CurrentWeather {
    LocalObservationDateTime: Date;
    Latitude: string;
    Longitude: string;
    LocationKey: string;
    LocalizedName: string;
    PrimaryPostalCode: string;
    Temperature: number;
    RealFeelTemperature: number;
    WeatherText: string;
    UvIndex: number;
    UvIndexText: string;
}
const currentWeather: CurrentWeather = JSON.parse(localStorage.getItem('currentWeather'));

一旦我解析了它,我想使用LocalObservationDateTime来获取小时数。但是出现错误,“无法读取未定义的属性'getHours'。”

 var localHour = currentWeather.LocalObservationDateTime.getHours();

看到某处Date必须是新的Date()。尝试过此操作,但不起作用。

  const localDate: Date = new Date(currentWeather.LocalObservationDateTime);
  const localDateHour = localDate.getHours();

1 个答案:

答案 0 :(得分:0)

我需要重命名每个属性以使其具有小写字母才能访问值。

export interface CurrentWeather {
    localObservationDateTime: Date;
    latitude: string;
    longitude: string;
    locationKey: string;
    localizedName: string;
    primaryPostalCode: string;
    temperature: number;
    realFeelTemperature: number;
    weatherText: string;
    uvIndex: number;
    uvIndexText: string;
}