網站搜尋

javascript - 使用 Date 的 now() 轉換為 America/Los_Angeles 的 Moment 時區


我想知道在 TypeScript 中是否有可能將 Date() 轉換為 moment().tz("America/Los_Angeles").format();

我已經嘗試過

import { MomentTimezone }  from 'moment-timezone';
const moment : MomentTimezone = new MomentTimezone(Date(), "America/Los_Angeles");

但是我有這個錯誤:

S2693: 'MomentTimezone' only refers to a type, but is being used as a value here

在做的時候

import * as moment from "moment-timezone";
let now = moment();

我有這個錯誤:

TS2349: This expression is not callable.   Type 'typeof import("C:/Users/sandro/IdeaProjects/booking/node_modules/moment/moment.d.ts")' has no call signatures.

和

const moment: MomentTimezone = {date: Date(), timezone: 'America/Los_Angeles'};

但我得到了

TS2322: Type '{ date: string; timezone: string; }' is not assignable to type 'MomentTimezone'.   Object literal may only specify known properties, and 'date' does not exist in type 'MomentTimezone'

答案#1

這段程式碼的問題——

import * as moment from "moment-timezone";

—意思是,在 ES6 中,import * as moment 語法將始終把 moment 導入為一個不可調用的模塊。

TypeScript 過去是不符合規範的,並且仍然允許你呼叫這些匯入。但在今天的 TS 中,這行不通。相反,我們使用較短的寫法:

import moment from "moment-timezone";

如果你使用那個代碼,那麼 moment().tz("America/Los_Angeles").format() 應該可以工作。

另見:

  • 理解 tsconfig 檔案中的 esModuleInterop