How to Get Current Date and Time in TypeScript
This article will walk you through how to get the current date and time in TypeScript.
Get Current Date and Time in TypeScript
We can acquire the existing date and time in TypeScript with the help of Date()
.
Example code:
# typescript
const newDate = new Date()
console.log(newDate)
Output:
We have used the Date()
constructor command to fetch the date object that denotes the current date and time in TypeScript.
Date objects collect numbers that denote the number of milliseconds passed since the 1st of January 1970 UTC and offer many innate methods.
Date Object Properties in TypeScript
The constructor
identifies the function that generates an object’s prototype. At the same time, the prototype
permits the addition of different properties and methods to an object.
We can enjoy many built-in methods that the Date
object offers by accurately inferring the Now
variable to be the Date
.
Let’s see some examples demonstrating the methods you can use on the Date
object.
Example code:
# typescript
const now =newDate();
console.log(now);
console.log(now.toLocaleDateString());
console.log(now.toLocaleString());
console.log(now.toUTCString());
console.log(now.toISOString());
Output:
Change Date Format in TypeScript
We can set the date format in many ways, such as YYYY-MM-DD
, MM/DD/YYYY
, and MM/DD/YYYY
. We can use either of these formats according to our needs.
On the other hand, time can be written as hh:mm:ss
.
Example code:
# typescript
function ConvertTo2Digits(newNum: number) {
return newNum.toString().padStart(2, '0');
}
function changeDateFormat(newDate: Date) {
return (
[
newDate.getFullYear(),
ConvertTo2Digits(newDate.getMonth() + 1),
ConvertTo2Digits(newDate.getDate()),
].join('-') +
' ' +
[
ConvertTo2Digits(newDate.getHours()),
ConvertTo2Digits(newDate.getMinutes()),
ConvertTo2Digits(newDate.getSeconds()),
].join(':')
);
}
console.log(changeDateFormat(new Date()));
console.log(changeDateFormat(new Date('May 16, 2020 02:34:07')));
Output:
In this function, six methods are shown associated with the date. We will discuss them in detail below.
The Date.getFullYear()
method gave back a four-digit number denoting the year related to a date.
The Date.getMonth()
method gave back an integer that is usually between 0
for January and 11
for December and denotes the month for a specified date. But unfortunately, this method has been dismissed by 1
.
The Date.getDate()
method gave back an integer between 1
and 31
and showed the day of the month for a defined date. The Date.getHours()
method gave back the hour for the defined date.
Then, the Date.getMinutes()
method returned the minutes for a specific date. And the Date.getSeconds()
method gave back the seconds of a fixed date.
We have to add 1
to the return value of getMonth()
because it is a zero-based method.
Convert Single Digits to Double Digits in TypeScript
Initially, we must create a ConvertTo2Digits()
function, which will ensure that a leading zero is added whenever a month, day, hours, minutes, or seconds only has a single-digit (are less than 10).
Example code:
# typescript
function ConvertTo2Digits(newNum: number){
return newNum.toString().padStart(2,'0');
}
console.log(ConvertTo2Digits(5));
console.log(ConvertTo2Digits(9));
console.log(ConvertTo2Digits(14));
Output:
We will use the padstart
method to ensure that we are getting consistent results and retain 2 digits for the month, days, hours, minutes, and seconds.
We will fix the total length of the string parameter to the ConvertTo2Digits()
function. This will ensure that this function will add a value under no circumstances if 2 digits are already present.
Add Hyphen Separator in Date in TypeScript
We have to place the year, month, and day in an array to join them by employing a hyphen separator.
Example code:
# typescript
console.log(['2022','05','16'].join('-'));
console.log(['2024','03','26'].join('-'));
Output:
We can also use another separator like a forward slash /
. With the help of this separator, we can effortlessly reorder the components of the date according to our liking.
For example, if we have MM/DD/YYYY
, we can change it to YYYY-MM-DD
by only changing places of the elements in the array. As a result, we have the date formatted as YYYY-MM-DD.
Change Time Format in TypeScript
Now, we will add the returned values from time-related methods in the form of an array and connect them with a colon, as shown below.
Example code:
# typescript
console.log(['03','11','17'].join(':'));
console.log(['06','22','49'].join(':'));
Output:
We can use the same methods to format the time component as we have used in the case of the date components.
Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.
LinkedIn