421

How do I express dates in TypeScript? Dates aren't a TypeScript type, so do I use any or object? Seems like there would be a "right" way to do:

let myDate: any = new Date();

I couldn't find much on Google, despite it being such a simple question.

Liam
  • 27,717
  • 28
  • 128
  • 190
VSO
  • 11,546
  • 25
  • 99
  • 187

4 Answers4

557

The type is Date:

const d: Date = new Date(); // but the type can also be inferred from "new Date()" already

It is the same as with every other object instance :)

Community
  • 1
  • 1
str
  • 42,689
  • 17
  • 109
  • 127
  • What is the name of the Set of `types` that includes `Date` as well as `Basic Types` referenced in OP? I am naming a module for extension methods. – ttugates Jan 02 '19 at 19:12
  • 3
    @ttugates Do you mean [union types](https://www.typescriptlang.org/docs/handbook/advanced-types.html#union-types) like for example `string | number | boolean | null | undefined | symbol | Date`? You could use a [type alias](https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-aliases) to avoid repetition. – str Jan 02 '19 at 20:26
  • Oh, no. Not sure of the scope of it.. But smth roughly analogous to .Net `system` types. See [Standard Built-in objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects). Is there a more concise widely used name? – ttugates Jan 02 '19 at 20:30
  • @ttugates Grouping primitive types and date objects together seems pretty arbitrary to me. I don't think there is a widely used name for that in JavaScript. Also, the original question is not related to your follow-up question. You should ask a new one instead. – str Jan 02 '19 at 20:34
  • Note that if you're using the two dates to find the difference, TypeScript will complain. A work-around is `const d: number = +new Date()` to coerce it to be a number: https://github.com/Microsoft/TypeScript/issues/5710 – Boris Yakubchik Jun 12 '19 at 11:20
  • 3
    "It is the same as with every other object instance :)" This is not exactly true. `string`, `number`, and `boolean` all user lower-case types in Typescript, so one might reasonably expect a `date` type to exist but they get an error when they try to use it. (at least, that's what brought me to this page) – Kip Oct 28 '19 at 15:13
  • @Kip TypeScript's lowercase types are used for primitive types. But [there are *also* the uppercase types which are different](https://stackoverflow.com/questions/14727044/typescript-difference-between-string-and-string). – str Oct 29 '19 at 16:24
  • Why is it that `date.setMonth(8)` gives `September`, instead of `August`? – Upulie Han Aug 04 '22 at 14:33
124

Every class or interface can be used as a type in TypeScript.

 const date = new Date();

will already know about the date type definition as Date is an internal TypeScript object referenced by the DateConstructor interface.

And for the constructor you used, it is defined as:

interface DateConstructor {
    new(): Date;
    ...
}

To make it more explicit, you can use:

 const date: Date = new Date();

You might be missing the type definitions though, the Date is coming for my example from the ES6 lib, and in my tsconfig.json I have defined:

"compilerOptions": {
    "target": "ES6",
    "lib": [
        "es6",
        "dom"
    ],

You might adapt these settings to target your wanted version of JavaScript.


The Date is by the way an Interface from lib.es6.d.ts:

/** Enables basic storage and retrieval of dates and times. */
interface Date {
    /** Returns a string representation of a date. The format of the string depends on the locale. */
    toString(): string;
    /** Returns a date as a string value. */
    toDateString(): string;
    /** Returns a time as a string value. */
    toTimeString(): string;
    /** Returns a value as a string value appropriate to the host environment's current locale. */
    toLocaleString(): string;
    /** Returns a date as a string value appropriate to the host environment's current locale. */
    toLocaleDateString(): string;
    /** Returns a time as a string value appropriate to the host environment's current locale. */
    toLocaleTimeString(): string;
    /** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */
    valueOf(): number;
    /** Gets the time value in milliseconds. */
    getTime(): number;
    /** Gets the year, using local time. */
    getFullYear(): number;
    /** Gets the year using Universal Coordinated Time (UTC). */
    getUTCFullYear(): number;
    /** Gets the month, using local time. */
    getMonth(): number;
    /** Gets the month of a Date object using Universal Coordinated Time (UTC). */
    getUTCMonth(): number;
    /** Gets the day-of-the-month, using local time. */
    getDate(): number;
    /** Gets the day-of-the-month, using Universal Coordinated Time (UTC). */
    getUTCDate(): number;
    /** Gets the day of the week, using local time. */
    getDay(): number;
    /** Gets the day of the week using Universal Coordinated Time (UTC). */
    getUTCDay(): number;
    /** Gets the hours in a date, using local time. */
    getHours(): number;
    /** Gets the hours value in a Date object using Universal Coordinated Time (UTC). */
    getUTCHours(): number;
    /** Gets the minutes of a Date object, using local time. */
    getMinutes(): number;
    /** Gets the minutes of a Date object using Universal Coordinated Time (UTC). */
    getUTCMinutes(): number;
    /** Gets the seconds of a Date object, using local time. */
    getSeconds(): number;
    /** Gets the seconds of a Date object using Universal Coordinated Time (UTC). */
    getUTCSeconds(): number;
    /** Gets the milliseconds of a Date, using local time. */
    getMilliseconds(): number;
    /** Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). */
    getUTCMilliseconds(): number;
    /** Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). */
    getTimezoneOffset(): number;
    /**
      * Sets the date and time value in the Date object.
      * @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT.
      */
    setTime(time: number): number;
    /**
      * Sets the milliseconds value in the Date object using local time.
      * @param ms A numeric value equal to the millisecond value.
      */
    setMilliseconds(ms: number): number;
    /**
      * Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC).
      * @param ms A numeric value equal to the millisecond value.
      */
    setUTCMilliseconds(ms: number): number;

    /**
      * Sets the seconds value in the Date object using local time.
      * @param sec A numeric value equal to the seconds value.
      * @param ms A numeric value equal to the milliseconds value.
      */
    setSeconds(sec: number, ms?: number): number;
    /**
      * Sets the seconds value in the Date object using Universal Coordinated Time (UTC).
      * @param sec A numeric value equal to the seconds value.
      * @param ms A numeric value equal to the milliseconds value.
      */
    setUTCSeconds(sec: number, ms?: number): number;
    /**
      * Sets the minutes value in the Date object using local time.
      * @param min A numeric value equal to the minutes value.
      * @param sec A numeric value equal to the seconds value.
      * @param ms A numeric value equal to the milliseconds value.
      */
    setMinutes(min: number, sec?: number, ms?: number): number;
    /**
      * Sets the minutes value in the Date object using Universal Coordinated Time (UTC).
      * @param min A numeric value equal to the minutes value.
      * @param sec A numeric value equal to the seconds value.
      * @param ms A numeric value equal to the milliseconds value.
      */
    setUTCMinutes(min: number, sec?: number, ms?: number): number;
    /**
      * Sets the hour value in the Date object using local time.
      * @param hours A numeric value equal to the hours value.
      * @param min A numeric value equal to the minutes value.
      * @param sec A numeric value equal to the seconds value.
      * @param ms A numeric value equal to the milliseconds value.
      */
    setHours(hours: number, min?: number, sec?: number, ms?: number): number;
    /**
      * Sets the hours value in the Date object using Universal Coordinated Time (UTC).
      * @param hours A numeric value equal to the hours value.
      * @param min A numeric value equal to the minutes value.
      * @param sec A numeric value equal to the seconds value.
      * @param ms A numeric value equal to the milliseconds value.
      */
    setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number;
    /**
      * Sets the numeric day-of-the-month value of the Date object using local time.
      * @param date A numeric value equal to the day of the month.
      */
    setDate(date: number): number;
    /**
      * Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC).
      * @param date A numeric value equal to the day of the month.
      */
    setUTCDate(date: number): number;
    /**
      * Sets the month value in the Date object using local time.
      * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively.
      * @param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used.
      */
    setMonth(month: number, date?: number): number;
    /**
      * Sets the month value in the Date object using Universal Coordinated Time (UTC).
      * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively.
      * @param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used.
      */
    setUTCMonth(month: number, date?: number): number;
    /**
      * Sets the year of the Date object using local time.
      * @param year A numeric value for the year.
      * @param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified.
      * @param date A numeric value equal for the day of the month.
      */
    setFullYear(year: number, month?: number, date?: number): number;
    /**
      * Sets the year value in the Date object using Universal Coordinated Time (UTC).
      * @param year A numeric value equal to the year.
      * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied.
      * @param date A numeric value equal to the day of the month.
      */
    setUTCFullYear(year: number, month?: number, date?: number): number;
    /** Returns a date converted to a string using Universal Coordinated Time (UTC). */
    toUTCString(): string;
    /** Returns a date as a string value in ISO format. */
    toISOString(): string;
    /** Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. */
    toJSON(key?: any): string;
}
k0pernikus
  • 60,309
  • 67
  • 216
  • 347
53

Typescript recognizes the Date interface out of the box - just like you would with a number, string, or custom type. So Just use:

myDate : Date;
David Haddad
  • 3,796
  • 8
  • 32
  • 40
1

As others have mentioned the type is Date.

This type is usefull when you want to enforce at compile time that you really have a Date object. Below is a mistake that is often make (forgetting the new keyword) and we can see that it is caught at compile time.

const date: Date = new Date();

function logDayNumber(date: Date){
    console.log(date.getDay())
} 

// Works fine
logDayNumber(date);

// Compile time error which happens when you forget new a String we be produced from Date()
// Argument of type 'string' is not assignable to parameter of type 'Date'
logDayNumber(Date());
Willem van der Veen
  • 33,665
  • 16
  • 190
  • 155