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”;反之不做处理