簡體   English   中英

格式化時間錯誤——“10.03”變成“10.3”

[英]Formatting time error - "10.03" becomes "10.3"

我有一個要格式化的日期和時間。 它大部分時間都有效,但如果時間在倒數第二個空格中有一個“0”,它將返回錯誤。 例如,時間“10.30”將被正確格式化,但“10.03”將返回不帶零的“10.3”。

我的代碼:

 const today: Date = new Date(); const date: Date = new Date(item.receivedDateTime); let time: string; if (date.getFullYear() === today.getFullYear() && date.getMonth() === today.getMonth() && date.getDate() === today.getDate()) { time = date.getHours() + ":" + date.getMinutes(); } else { time = date.getDate() + "/" + (date.getMonth() + 1); }

以上將錯誤地格式化時間。 代碼有什么問題? 我不想使用 padstart,因為它在 IE11 或 moment.js 中不受支持。

您可以將date.getMinutes()的值保存在一個變量中,並檢查它是否小於 10,如果是,則附加一個0

const minutes = date.getMinutes();
const formattedMinutes = (minutes < 10) ? '0' + minutes : minutes;

最后,使用格式化值輸出:

time = date.getHours() + ":" + formattedMinutes;

您可以使用簡單的墊功能

 const pad = num => ("0"+num).slice(-2); const item = {"receivedDateTime":1570000000000} const today = new Date(); const date = new Date(item.receivedDateTime); let time = ""; if (date.getFullYear() === today.getFullYear() && date.getMonth() === today.getMonth() && date.getDate() === today.getDate()) { time = pad(date.getHours()) + ":" + pad(date.getMinutes()); } else { time = pad(date.getDate()) + "/" + pad(date.getMonth() + 1); } console.log(time)

代替,

time = date.getHours() + ":" + date.getMinutes();

您可以使用,

var minutes = d.getMinutes() > 9 ? d.getMinutes() : '0' + d.getMinutes();
time = date.getHours() + ":" + minutes

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM