Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript thinks getYear does not exist on type Date

I'm running tsc inside a webpack project, with "core-js": "registry:dt/core-js#0.0.0+20160725163759" and "node": "registry:dt/node#6.0.0+20160909174046"

Other date properties work fine:

private dateToString (date: Date) {
    let month = date.getMonth();
    let day = date.getDate();
    let year = date.getYear() + 1900;

    let dateString = `${month}/${day}/${year}`;
    return dateString;      
}

Typescript recognizes date.getMonth and date.getDate just fine, but on date.getYear it gives

Property 'getYear' does not exist on type 'Date'.

What definition am I missing?

like image 282
A. Duff Avatar asked Oct 31 '16 20:10

A. Duff


2 Answers

That API is deprecated. Try getFullYear() instead.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getYear

This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.

The getYear() method returns the year in the specified date according to local time. Because getYear() does not return full years ("year 2000 problem"), it is no longer used and has been replaced by the getFullYear() method.

like image 189
Drew Noakes Avatar answered Nov 04 '22 08:11

Drew Noakes


Change this line from

let year = date.getYear() + 1900;

to

let year = date.getFullYear();
like image 4
Jerry Chong Avatar answered Nov 04 '22 06:11

Jerry Chong