Typescript date type format

TypeScript Date (With Examples)

In this TypeScript tutorial, we will discuss the TypeScript Date. We will discuss how to create a date object in TypeScript. We will also discuss how to add days to date in typescript, date format in typescript, typescript date now, etc.

If you are new to TypeScript, read my previous article on the typescript hello world program for beginners.

TypeScript Date

The Date object represents a date and time functionality in TypeScript. We used date object to get or set the year, month and day, hour, minute, second, millisecond, etc in TypeScript.

TypeScript provides a Date library to perform an operation on Dates. Calling new Date() creates today’s Date.

Creating Date Object in TypeScript

new Date(): To create a new date object, there are four ways.

let date: Date = new Date(); console.log(date) //output: 2019-05-27T11:53:32.118Z

new Date(milliseconds): It creates a new date object as zero time plus milliseconds.

let date: Date = new Date(1600000000000); console.log(date) //output: 2020-09-13T12:26:40.000Z

new Date(datestring): It creates a new date object from a date string.

let date: Date = new Date("2019-05-27"); console.log(date) //output: 2019-05-27T00:00:00.000Z

new Date ( year, month, date[, hour, minute, second, millisecond ]): It creates a new date object with a specified date and time.

let date: Date = new Date(2019,0o4,27,18,0o1,30,15); console.log(date) //output: 2019-05-27T18:01:30.015Z

We can access date components using various get methods.

let date: Date = new Date(); console.log("Day: "+date.getDay()) console.log("Date: "+date.getDate()) console.log("Month: "+date.getMonth()) console.log("Year: "+date.getFullYear()) //output: Day: 1 Date: 27 Month: 4 Year: 2019

We can set date components using various set methods.

let date: Date = new Date(); date.setDate(27) date.setMonth(0o5) date.setFullYear(2019) console.log("Date: "+date.getDate()) console.log("Month: "+date.getMonth()) console.log("Year: "+date.getFullYear()) //output: Date: 27 Month: 5 Year: 2019

You may like the following TypeScript Tutorials:

  • TypeScript Enum (With Examples)
  • TypeScript Dictionary (With Examples)
  • TypeScript Map (Detailed Tutorial with Examples)
  • TypeScript Set and Weakset (with Examples)
  • Typescript hello world program for beginners

I Hope, this typescript tutorial helps to learn typescript date.

I am Bijay a Microsoft MVP (8 times – My MVP Profile) in SharePoint and have more than 15 years of expertise in SharePoint Online Office 365, SharePoint subscription edition, and SharePoint 2019/2016/2013. Currently working in my own venture TSInfo Technologies a SharePoint development, consulting, and training company. I also run the popular SharePoint website EnjoySharePoint.com

Читайте также:  Java debug unit test

Источник

TypeScript Dates: How To Create And Use TS Dates And Times

TypeScript Dates

TypeScript dates are well supported and don’t represent any big departure from JavaScript. Learn more about them below.

TypeScript Dates

TypeScript recognizes JavaScript’s Date interface out of the box to represent single moments in time. The most important value of Date objects is the number of milliseconds since the epoch (January 1, 1970).

Remember that TypeScript uses UTC as the primary time standard, allowing it to work with all local time zones if necessary.

Create A Date Object

You can use Date() as either a function or a constructor (with the new keyword).

As a constructor, it creates and returns a Date object representing a date and time that you require. When invoked as a function, the returned value is a string that represents the current date and time. All the arguments you provide will be ignored.

Remember those critical differences or you might end up with type-related errors in TypeScript.

new Date()

There are multiple ways to use the Date() constructor. Here are some common variants of its syntax:

new Date() new Date(value) new Date(dateObject) new Date(dateString) new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds)

When you call the constructor without any argument, it will return a Date object representing the date and time at the time it is called.

let currentDate: Date; currentDate = new Date(); console.log(currentDate);

The first statement tells TypeScript currentDate is an instance of the interface Date. Then we assign the object returned by the Date() constructor to it.

currentDate is now a Date object that represents the moment in time when Date() is invoked. The console.log() method can print its string representation to the console.

You can provide the Date() constructor with an integer value to create an object representing a number of milliseconds from the ECMAScript epoch. Remember that this argument doesn’t take leap seconds into account.

let date1: Date = new Date(1000000000); console.log(date1);

In this example, the date1 object now points to a point that is 1000000000 milliseconds from the epoch, or around midday on January 12, 1970.

Читайте также:  Java virtual machine window 7

The range of this integer value should be within 8,640,000,000,000,000 and -8,640,000,000,000,000. Otherwise, the constructor will return a Date object whose string representation is “Invalid Date”.

Another argument you can provide the Date() constructor is a string that represents a date in the ISO 8601 format (YYYY-MM-DDTHH:mm:ss.sssZ).

The constructor will use the Date.parse() method under the hood to parse your input and create a Date object accordingly. It treats date-only strings (such as “2022-11-01” as UTC, and date-time strings (like “2022-11-01T12:00” as local.

let date1: Date = new Date("2022-11-01"); console.log(date1);

If you already have a Date object, you can parse it to the Date() constructor too. A copy of the existing object will be created.

One of the most popular uses of the Date() constructor invokes individual component values of date and time. You can set the year, month, day, hours, minute, second, and millisecond for the Date object, all evaluated against your system’s local time zone.

Date() doesn’t require you to provide a value for every component. Any missing values will be filled automatically by the system, using the lowest possible values. In the simplest form, all you need is the year and month components.

let date1: Date = new Date(2022, 10); console.log(date1); console.log(date1.toLocaleString());
2022-10-31T17:00:00.000Z 11/1/2022, 12:00:00 AM

This example gives Date() only two components and will treat them as the year and month, respectively. Other fields will be filled by Date(), with 1 for day and 0 for other components).

However, if you print this Date object with console.log(), the output doesn’t look like what we have just described.

The reason is that this method produces the string representation in UTC, while the Date() constructor evaluates the date and time components in local time. You will need to use the toLocaleString() method, which returns the representation of the date and time in local time.

Date()

When you use Date() as a function, the returned value is a string. It can only produce the representation for the current date and time.

let date2: string; date2 = Date(); console.log(date2);
Sat Oct 08 2022 16:43:54 GMT+0700 (Indochina Time)

There is no object created, and you should use the string type to get the returned value of the Date() function.

Читайте также:  Php sort array associative arrays

Date Methods

TypeScript Date objects support similar methods to those of Date objects in JavaScript.

If you want to get a specific component from a Date object, use these simple methods: getDate(), getDay(), getFullYear(), getMonth(), getHours(), get Minutes(), getSeconds(), getMilliseconds(), and so on.

Besides some exceptions, their purposes are quite self-explanatory:

let currentDate: Date = new Date(); console.log( currentDate.getFullYear(), currentDate.getMonth(), currentDate.getMonth(), currentDate.getDate(), currentDate.getDay(), currentDate.getHours(), currentDate.getMinutes(), currentDate.getMinutes(), currentDate.getSeconds() );

Remember that getDay() returns the day of the week, while getDate() returns the day of the month of a specific date.

Additionally, all those methods return values according to local time. Use their UTC versions (such as getUTCDate()) to get results in that time standard.

You can alter any component of an existing Date object with setFullYear(), setMonth(), setDate(), setHours(), setMinutes(), setSeconds(), setMilliseconds(), as well as the UTC versions.

let currentDate: Date = new Date(); console.log("Old date and time:", currentDate.toLocaleString()); currentDate.setFullYear(2020); currentDate.setMonth(3); currentDate.setDate(8); console.log("New date and time:", currentDate.toLocaleString());
Old date and time: 10/8/2022, 5:01:49 PM New date and time: 4/8/2020, 5:01:49 PM

To get the string representations of Date objects, use methods such as toDateString(), toTimeString(), toString(), etc.

Each of them typically has two other versions. For example, the toString() method interprets the Date object in the local timezone, toUTCString() in the UTC timezone, and toLocaleString() uses its language-sensitive representation.

let currentDate: Date = new Date(); console.log(currentDate.toString()); console.log(currentDate.toUTCString()); console.log(currentDate.toLocaleString());
Sat Oct 08 2022 17:07:02 GMT+0700 (Indochina Time) Sat, 08 Oct 2022 10:07:02 GMT 10/8/2022, 5:07:02 PM

Tutorials about TypeScript Dates

Summary

It is easy to transition to TypeScript dates if you are already familiar with those objects in JavaScript. Even when this isn’t the case, you should still have a solid understanding of this interface with the explanation above.

My name is Robert. I have a degree in information technology and two years of expertise in software development. I’ve come to offer my understanding on programming languages. I hope you find my articles interesting.

Job: Developer
Name of the university: HUST
Major: IT
Programming Languages: Java, C#, C, Javascript, R, Typescript, ReactJs, Laravel, SQL, Python

Источник

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