javascript - Date kullanarak now() değerini America/Los_Angeles zaman diliminde Moment Timezone'a dönüştürmek
Typescript'te Date()'yi moment().tz("America/Los_Angeles").format();'e dönüştürmenin mümkün olup olmadığını bilmek isterim.
Denedim
import { MomentTimezone } from 'moment-timezone';
const moment : MomentTimezone = new MomentTimezone(Date(), "America/Los_Angeles");
ama bu hatayı alıyorum:
S2693: 'MomentTimezone' only refers to a type, but is being used as a value here
yaparken
import * as moment from "moment-timezone";
let now = moment();
Bu hatayı alıyorum:
TS2349: This expression is not callable. Type 'typeof import("C:/Users/sandro/IdeaProjects/booking/node_modules/moment/moment.d.ts")' has no call signatures.
ve
const moment: MomentTimezone = {date: Date(), timezone: 'America/Los_Angeles'};
ama aldım
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'
Cevap #1
Bu kodla ilgili sorun—
import * as moment from "moment-timezone";
—ES6'da, import * as moment sözdiziminin her zaman moment'i çağrılamayan bir modül olarak içe aktaracağıdır.
TypeScript eskiden uyumlu değildi ve bu importları yine de çağırmanıza izin veriyordu. Ama bu, günümüz TS'sinde işe yaramaz. Bunun yerine, daha kısa olanı kullanıyoruz:
import moment from "moment-timezone";
Eğer o kodu kullanırsanız, moment().tz("America/Los_Angeles").format() çalışmalıdır.
Ayrıca bakınız:
- tsconfig dosyasında esModuleInterop'i Anlamak
