I am using method to get data
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); }
And as output I get
2017-6-13 20:36:6
I would like to get the same thing, but like
2017-06-13 20:36:06
But if I try one of the lines, that I commented out, for example this one
month = '0' + month;
I get error
Argument of type 'string' is not assignable to parameter of type 'number'.
How could I concat string and number?
TypeScript | String concat() Method The concat() is an inbuilt function in TypeScript which is used to add two or more strings and returns a new single string. Syntax: string. concat(string2, string3[, ..., stringN]);
In javascript, we can also concatenate strings with variables. We can do more than concatenate strings in Javascript: we can concatenate integers and booleans to strings.
In TypeScript, the string is an object which represents the sequence of character values. It is a primitive data type which is used to store text data. The string values are surrounded by single quotation mark or double quotation mark. An array of characters works the same as a string.
A string and an integer value are added, and the result is an integer value. Concatenation operator ('. ')
Union Types
You can use a union type when declaring variables.
let month: string | number = currentTime.getMonth(); if (month < 10) { month = '0' + month; }
Template literals (ES6+)
Alternatively you can create a new variable and use a template literal
const paddedMonth: string = `0${month}`;
Your string concatenation then turns into this for example:
str = `${year}-${paddedMonth}-${day} ${hours}:${minutes}:${seconds} `;
Much more readable, IMO.
if you want to work with date, you can use momentjs module: https://momentjs.com
moment().format('MMMM Do YYYY, h:mm:ss a'); // July 13th 2017, 11:18:05 pm moment().format('dddd'); // Thursday moment().format("MMM Do YY"); // Jul 13th 17 moment().format('YYYY [escaped] YYYY'); // 2017 escaped 2017 moment().format(); // 2017-07-13T23:18:05+04:30
and about the error you got,you most use like this:
let monthStr: string = month; if ( month < 10) { monthStr = '0' + month; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With