我正在使用方法获取数据
function date() {
let str = '';
const currentTime = new Date();
const year = currentTime.getFullYear();
const month = currentTime.getMonth();
const day = currentTime.getDate();
const hours = currentTime.getHours();
let minutes = currentTime.getMinutes();
let seconds = currentTime.getSeconds();
if (month < 10) {
//month = '0' + month;
}
if (minutes < 10) {
//minutes = '0' + minutes;
}
if (seconds < 10) {
//seconds = '0' + seconds;
}
str += year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds + ' ';
console.log(str);
}
作为输出我得到了
2017-6-13 20:36:6
我想得到同样的东西,但是喜欢
2017-06-13 20:36:06
但是如果我尝试其中一行,我注释掉了,例如这一行
month = '0' + month;
我收到错误
Argument of type 'string' is not assignable to parameter of type 'number'.
如何连接字符串和数字?
最佳答案
联合类型
您可以使用 union type声明变量时。
let month: string | number = currentTime.getMonth();
if (month < 10) {
month = '0' + month;
}
模板文字 (ES6+)
或者,您可以创建一个新变量并使用 template literal
const paddedMonth: string = `0${month}`;
例如,您的字符串连接会变成这样:
str = `${year}-${paddedMonth}-${day} ${hours}:${minutes}:${seconds} `;
更具可读性,IMO。
关于javascript - 如何在 Typescript 中连接字符串和数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45088700/