EN
TypeScript - get current date only
0 points
In TypeScript we use Date
class to get current time.
xxxxxxxxxx
1
const now: Date = new Date();
2
3
// Current date: Thu Feb 20 2020
4
console.log('Current date: ' + now.toDateString());
Example output:
xxxxxxxxxx
1
Current date: Wed Mar 02 2022
Note: during using
to...String
methods it is necessaryto be careful because of specific formatting of date and time on the locale.
xxxxxxxxxx
1
// ONLINE-RUNNER:browser;
2
3
function renderNumber(value: number, length: number) {
4
let result: string = value.toString();
5
6
for (; length > result.length; length -= 1) result = '0' + result;
7
8
return result;
9
}
10
11
const now: Date = new Date();
12
13
const year: number = now.getFullYear();
14
const month: number = now.getMonth() + 1;
15
const day: number = now.getDate();
16
17
const date: string =
18
renderNumber(year, 4) +
19
'.' +
20
renderNumber(month, 2) +
21
'.' +
22
renderNumber(day, 2);
23
24
console.log('Current date: ' + date); // Current date: 2022.03.02