let now = new Date(); this.nowYear = now.getFullYear(); this.nowMonth = now.getMonth() + 1; let nowweekday = now.getDate(); let nowMonths; let nowweekdays; if (this.nowMonth < 10) { nowMonths = "0" + this.nowMonth; } else { nowMonths = this.nowMonth; } if (nowweekday < 10) { nowweekdays = "0" + nowweekday; } else { nowweekdays = nowweekday; } let hh = now.getHours(); //時 let mm = now.getMinutes(); //分 let ss = now.getSeconds(); //秒 let hhs, mms, sss; if (hh < 10) { hhs = "0" + hh; } else { hhs = hh; } if (mm < 10) { mms = "0" + mm; } else { mms = mm; } if (ss < 10) { sss = "0" + ss; } else { sss = ss; } this.XXlabel.text = this.nowYear + "-" + nowMonths + "-" + nowweekdays + " " + hhs + ":" + mms + ":" + sss;
若是做時間控件的話,考慮到時間格式統一,可以單獨設置一個函數,將傳入的時間數字同“10”進行比較,若小於則前加“0”;反之不做處理