TypeScript Date object represents an instant in the timeline and enables basic storage and retrieval of dates and times. By default, a new Date() object contains the date and time of the user’s computer. We can get or set the year, month and day, hour, minute, second, and millisecond information of a Date object.

TypeScript Date type is imported from /lib/lib.es6.d.ts. It is implicitly inferred, just like string, number or boolean types.

//Type is inferred
let date = new Date();

//explicit type declaration
let date: Date = new Date();

Do not forget to target TypeScript transpiler to ES6. We can target it either from command line using '--target es6' or configure in tsconfig.json.

{
  "compilerOptions": {
  	...
    "target": "es6",
    ...
  },
  "lib": [
    "es6",
    "dom"
  ]
}

1. Creating a New Date

Date objects are created with the new Date() constructor. The default constructor creates a new date object with the browser’s current date, time and timezone.

const d = new Date();   //Thu Nov 03 2022 14:21:47 GMT+0530 (India Standard Time)

The Date constructor accepts the following parameters to create a specific date and time value.

  • timestamp number
  • date string
  • date object
  • exact date and time component values (year, monthIndex, day, hours, minutes, seconds, milliseconds), The year and monthIndex are mandatory parameters. The default value of day is 1. The default value of time components is 0. Months are 0-indexed.
const date = new Date(628021800000); 	//timestamp number  

const date = new Date('December 17, 2021 04:28:00');	//date string

const date = new Date(2021, 11, 17); //year, month, day
const date = new Date(2021, 11, 17, 4, 28, 0);	//year, month, day, hours, minutes, seconds

To create current Date and Time in UTC, use the Date.UTC() method. It accepts the same argument as the constructor but converts them to the UTC timezone.

const utcDate = new Date(Date.UTC(2021, 11, 17, 4, 28, 0));	

2. Get Current Date and Time

The Date.now() method returns the numeric value in milliseconds of the current date and time since epoch. This numeric value is good enough for comparing the timestamps or passing to the APIs in the application logic.

const currentTimeInMillis = Date.now();	//1667466497314

We can use the new Date() constructors and call the specific get() methods to get the other date and time parts.

  • getDate(): returns the day of the month (1 – 31).
  • getDay(): returns the day of the week (0 – 6).
  • getMonth(): returns the month (0 – 11).
  • getYear(): returns the year (usually 2–3 digits).
  • getFullYear(): returns the year (4 digits for 4-digit years).
  • getHours(): returns the hour (0 – 23).
  • getMinutes(): returns the minutes (0 – 59).
  • getSeconds(): returns the seconds (0 – 59).
  • getMilliSeconds(): returns the milliseconds (0 – 999).
  • getTime(): returns the numeric value of the date as the number of milliseconds since epoch.
  • getTimezoneOffset(): returns the time-zone offset in minutes for the current locale.
const currentDate = new Date();		//Thu Nov 03 2022 14:46:40 GMT+0530 (India Standard Time) {}

currentDate.getDate();			//3
currentDate.getDay();				//4
currentDate.getMonth();			//10
currentDate.getYear();			//122
currentDate.getFullYear();	//2022
currentDate.getHours();			//14
currentDate.getMinutes();		//46
currentDate.getSeconds();		//40
currentDate.getMilliseconds();		//577
currentDate.getTimezoneOffset();	//-330

Note that Date object provides separate methods to get the date and time information in UTC (Universal Time).

  • getUTCDate(): returns the day of the month (1 – 31) in UTC.
  • getUTCDay(): returns the day of the week (0 – 6) in UTC.
  • getUTCMonth(): returns the month (0 – 11) in UTC.
  • getUTCYear(): returns the year (usually 2–3 digits) in UTC.
  • getUTCFullYear(): returns the year (4 digits for 4-digit years) in UTC.
  • getUTCHours(): returns the hour (0 – 23) in UTC.
  • getUTCMinutes(): returns the minutes (0 – 59) in UTC.
  • getUTCSeconds(): returns the seconds (0 – 59) in UTC.
  • getUTCMilliSeconds(): returns the milliseconds (0 – 999) in UTC.

3. Modifying a Date

We can modify a Date object using its set() methods for the specific date and time parts.

For example, we can add days to a Date using the setDate() method.

date.setDate(date.getDate() + 5);		//adding 5 days to current date

Note that if the dayValue is outside of the range of date values for the month, setDate() will update the Date object accordingly. This is true for other set() methods as well.

date.setDate(date.getDate() + 35);		//Shift the month to next month and set the day accordingly

The other set() methods are:

  • setDate(number): changes the day of the month of a given Date instance.
  • setMonth(number): changes the month of a given Date instance.
  • setFullYearnumber): changes the year of a given Date instance.
  • setHours(number): changes the hours of a given Date instance.
  • setMinutes(number): changes the minutes of a given Date instance.
  • setSeconds(number): changes the seconds of a given Date instance.
  • setMilliseconds(number): changes the milliseconds of a given Date instance.
  • setTime(number): sets the Date object to the time represented by a number of milliseconds since epoch.

Similar methods are available for setting the date and time parts in UTC, similar to get() methods seen above.

4. Comparing Two Date Objects

The correct way to compare two Date objects is by using the method getTime().

let dateOne = new date('2022-01-10T00:00:00.000Z');
let dateTwo = new date('2022-02-10T00:00:00.000Z');

dateOne.getTime() == dateTwo.getTime();   //false
dateOne.getTime() > dateTwo.getTime();   	//false
dateOne.getTime() < dateTwo.getTime();   	//true

Remember that do not compare the date object variables, and they will not give correct and consistent results.

dateOne == dateTwo;		//NEVER DO THIS !!

5. Formatting a Date

We may need to format the Date object for printing on the UI. The Date object provides following inbuilt methods for printing the date in specific formats.

const today = new Date(2022, 10, 3);

today.toString() // Thu Nov 03 2022 00:00:00 GMT+0530 (India Standard Time)
today.toDateString() // Thu Nov 03 2022
today.toISOString() // 2022-11-02T18:30:00.000Z
today.toLocaleDateString() // 11/3/2022 (current locale specific pattern)

To format the date string into a specific locale, we can pass the locale string as a parameter to the toLocaleDateString() method.

today.toLocaleDateString('en-GB')	// 03/11/2022

Sometimes, we need to format the date in a custom format that is not available using default methods. In such cases, we can retrieve the specific date and time information from the Date object and construct the display string ourselves.

function format(inputDate) {
  let date, month, year;

  date = inputDate.getDate();
  month = inputDate.getMonth() + 1;
  year = inputDate.getFullYear();

  date = date.toString().padStart(2, '0');
  month = month.toString().padStart(2, '0');

  return `${date}/${month}/${year}`;
}

6. Conclusion

In this typescript tutorial, we learned to work with Date object. We learned to create new Date objects, and modify, compare and format them to custom and inbuilt patterns.

Happy Learning !!

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial