为什么当我用变量附加到 LocaleString() 时不能使用 getFullYear() 或任何其他函数?


let new_date = new Date().toLocaleString("en-US", { timeZone: 'Asia/Qatar', timeStyle: "medium", hourCycle: "h12" });
console.log(new_date.getFullYear())

原因是toLocaleString返回的是string,而不是日期,参见date . tolocalestring()返回值

let new_date = new Date().toLocaleString("en-US", { timeZone: 'Asia/Qatar', timeStyle: "medium", hourCycle: "h12" });
console.log('new_date type:', typeof new_date)

如果您使用日期/时间库,如luxon,您可以在所需的区域创建一个DateTime对象。这有一个.year属性,它将为您提供完整的年份:

let { DateTime } = luxon;
console.log("Time:", DateTime.fromJSDate(new Date(), { zone: 'Asia/Qatar'}).toISO())
console.log("Year:", DateTime.fromJSDate(new Date(), { zone: 'Asia/Qatar'}).year)
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.0.1/luxon.min.js" integrity="sha512-bI2nHaBnCCpELzO7o0RB58ULEQuWW9HRXP/qyxg/u6WakLJb6wz0nVR9dy0bdKKGo0qOBa3s8v9FGv54Mbp3aA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

最新更新