Получить текущее время typescript

How to get the current date in TypeScript

The Date object is used to get the current date in TypeScript. We can use it to get the current date-time and also change it to different formats.

Different types of Date() object constructor:

We can create a new Date object and each time we create a Date object, it returns the current date-time.

There are different ways to construct a Date object with its constructor.

The constructor is not taking any parameters. It will create one Date object with current date and time.

We can pass the number of milliseconds since January 1, 1970, 00:00:00 UTC.

It takes a string that represents a date. It is advised to use ISO 8601 format strings YYYY-MM-DDTHH:mm:ss.sssZ *.*If the string includes the only date part, it is treated as UTC. If we also pass the time without a timezone, it will be considered local.

If we pass a date object, it creates a copy of that date object with equivalent data and returns that object.

5. new Date(year, month, day, hour, min, seconds, ms)

We can pass the year, month, day, hour, minute, seconds, and milliseconds values to the constructor of Date to create a Date object. Here, year and month are required. Other values are optional. The value starts from 1 for day and it starts from 0 for all other parameters.

Get the current date in TypeScript by using the Date constructor:

Let’s use the Date constructor to get the current date:

let date = new Date(); console.log(date);

It will print the date-time string as like below:

Useful methods to represent the date in different ways:

We can use the below methods to represent the current date-time in different ways:

It returns the date part of the object in human-readable format.

It converts the date to a string in ISO 8601 format

Locality sensitive representation of the date portion of the date object.

Locality sensitive representation of the date object.

Locality sensitive representation of the time portion of the date object.

String representation of the date object.

Date to a string using UTC timezone.

let date = new Date(); console.log(date.toDateString()); // Sun Jul 10 2022 console.log(date.toISOString()); // 2022-07-10T06:03:56.241Z console.log(date.toLocaleDateString()); // 10/7/2022 console.log(date.toLocaleString()); // 10/7/2022, 11:33:56 am console.log(date.toLocaleTimeString()); // 11:33:56 am console.log(date.toString()); // Wed Jul 10 2022 11:33:56 GMT+0530 (India Standard Time) console.log(date.toUTCString()); // Wed, 10 Jul 2022 06:03:56 GMT

Method 2: Get the year, month and day:

Date object also provides different getter methods. We can use these methods to create our own date string. For example:

let date = new Date(); let today = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate(); console.log(today);

It will print something like below:

Читайте также:  Center image and text css

Get current date yyyy-mm-dd

As shown in the above example, we can change the date string to any format we want. For example,

const padZero = (num: number, pad: number) => num.toString().padStart(pad, '0'); let date = new Date(); let today = date.getFullYear() + "-" + padZero((date.getMonth() + 1), 2) + "-" + padZero(date.getDate(), 2); console.log(today);

Here, we created one new function padZero that will add zeroes to the start of a number to convert it to a fixed length string.

It will create date of yyyy-mm-dd.

Источник

Get Current Date and Time in TypeScript

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() .

# typescript const newDate = new Date() console.log(newDate) 

Get Current Date and Time Using new Date() in TypeScript

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.

# typescript const now =newDate();  console.log(now); console.log(now.toLocaleDateString()); console.log(now.toLocaleString()); console.log(now.toUTCString()); console.log(now.toISOString()); 

Date Object Properties in TypeScript

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 .

# 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'))); 

Change Date Format Using a Function in TypeScript

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).

# typescript function ConvertTo2Digits(newNum: number) return newNum.toString().padStart(2,'0'); >  console.log(ConvertTo2Digits(5)); console.log(ConvertTo2Digits(9)); console.log(ConvertTo2Digits(14)); 

Convert Single Digits to Double Digits in TypeScript

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.

# typescript console.log(['2022','05','16'].join('-')); console.log(['2024','03','26'].join('-')); 

Add a Hyphen in Date in TypeScript

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.

# typescript console.log(['03','11','17'].join(':')); console.log(['06','22','49'].join(':')); 

Change Time Format in TypeScript

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.

Related Article — TypeScript Date

Источник

Получить текущее время typescript

Last updated: Jan 20, 2023
Reading time · 3 min

banner

# Get the current date and time in TypeScript

Use the Date() constructor to get the current date and time in TypeScript, e.g. const now = new Date() .

When the Date() constructor is called without any arguments, it returns a Date object that represents the current date and time.

Copied!
// 👇️ const now: Date const now = new Date(); console.log(now); // 👉️ 2023-01-20T12:01:02.900Z

We called the Date() constructor to get a Date object that represents the current date and time in TypeScript.

Date objects store a number that represents the number of milliseconds elapsed since the 1st of January 1970 UTC.

The type of the now variable is correctly inferred to be Date which enables us to use any of the built-in methods the Date object implements.

# Examples of commonly used Date object methods

Here are some examples of methods you might use on the Date object.

Copied!
// 👇️ const now: Date const now = new Date(); console.log(now); // 👉️ 2023-01-20T12:01:41.216Z console.log(now.toLocaleDateString()); // 👉️ 1/20/2023 console.log(now.toLocaleString()); // 👉️ 1/20/2023, 2:01:41 PM console.log(now.toUTCString()); // 👉️ Fri, 20 Jan 2023 12:01:41 GMT console.log(now.toISOString()); // 👉️ 2023-01-20T12:01:41.216Z

# Formatting the current date and time using TypeScript

Here is an example that formats the date and time as YYYY-MM-DD hh:mm:ss , but can easily be tweaked to other formats, e.g. to MM/DD/YYYY or MM/DD/YYYY hh:mm:ss .

Copied!
function padTo2Digits(num: number) return num.toString().padStart(2, '0'); > function formatDate(date: Date) return ( [ date.getFullYear(), padTo2Digits(date.getMonth() + 1), padTo2Digits(date.getDate()), ].join('-') + ' ' + [ padTo2Digits(date.getHours()), padTo2Digits(date.getMinutes()), padTo2Digits(date.getSeconds()), ].join(':') ); > // 👇️ YYYY-MM-DD hh:mm:ss // 👇️ "2023-01-20 14:03:10" (Current date and time) console.log(formatDate(new Date())); // 👇️️ 2025-05-04 05:24:07 (yyyy-mm-dd hh:mm:ss) console.log(formatDate(new Date('May 04, 2025 05:24:07')));

The function makes use of the following 6 methods on the Date object:

  • Date.getFullYear method — returns a four-digit number representing the year that corresponds to a date.
  • Date.getMonth — returns an integer between 0 (January) and 11 (December) and represents the month for a given date. Yes, unfortunately, the getMonth method is off by 1 .
  • Date.getDate — returns an integer between 1 and 31 representing the day of the month for a specific date.
  • Date.getHours — returns the hour for the specified date.
  • Date.getMinutes — returns the minutes for a date.
  • Date.getSeconds — returns the seconds of a specific date.

The getMonth method returns a zero-based month index from 0 to 11, meaning January is 0 and December is 11 .

The getMonth method is zero-based, so we added 1 to its return value.

We first created a padTo2Digits function that takes care of adding a leading zero if the month, day, hours, minutes or seconds only contain a single digit (are less than 10).

Copied!
function padTo2Digits(num) return num.toString().padStart(2, '0'); > console.log(padTo2Digits(3)); // 👉️ '03' console.log(padTo2Digits(7)); // 👉️ '07' console.log(padTo2Digits(10)); // 👉️ '10'

We want to make sure that the result is always consistent and has 2 digits for the months, days, hours, minutes and seconds, so we used the padStart method.

The first parameter we passed to the padTo2Digits function is the total length of the string, so it will never pad a value if it already has 2 digits.

We placed the year, month and day in an array, so we can join them with a hyphen separator.

Copied!
console.log(['2023', '02', '17'].join('-')); // 👉️ '2023-02-17' console.log(['2024', '07', '24'].join('-')); // 👉️ '2024-07-24'

This could have been any other separator, e.g. a forward slash / .

You could also easily reorder the date components if necessary (e.g. to MM/DD/YYYY ) by switching the places of the elements in the array.

This gets us the date formatted as YYYY-MM-DD .

The next step is to place the return values of the time-related methods in an array and join them with a colon separator.

Copied!
console.log(['06', '30', '17'].join(':')); // 👉️ '06:30:17' console.log(['09', '11', '49'].join(':')); // 👉️ '09:11:49'

We used the same approach to format the time component as we did with the date components.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью