1

I want to get the date in the format: 15-10-19

But for some reason, it writes: 15-10-119. I have no idea why it writes 119 as year. (Notice, I don't want the full year.

Here is my code

var today = new Date();
var dd = String(today.getDate());
var mm = String(today.getMonth() + 1);
var yy = today.getYear();
var dateToday = dd+"-"+mm+"-"+yy;
console.log(dateToday);
jeprubio
  • 17,312
  • 5
  • 45
  • 56
user1960836
  • 1,732
  • 7
  • 27
  • 47
  • 2
    `.getYear()` returns `119` for `2019`, since it considers `19` to be `1919`. – VLAZ Oct 15 '19 at 07:32
  • The other question is closed as a dupe to another question, so you have to follow that. The "main dupe" has a better solution with using `toLocaleDateString`, while the other one just uses string manipulation. – VLAZ Oct 15 '19 at 07:35

5 Answers5

2

This will work:

To show last two digits of the year:

 var yy = today.getFullYear().toString().substr(-2); // 19

To show full year:

 var yy = today.getFullYear(); // 2019
Santosh Jadi
  • 1,479
  • 6
  • 29
  • 55
2

In order to get the last two characters from the current year you can use: var yy = new Date().getFullYear().toString().substr(-2);

TeslaXba
  • 347
  • 4
  • 22
  • This solution was what I was thinking at first, but was hoping there was a better one that I didn't know of :D – user1960836 Oct 15 '19 at 07:43
  • 1
    If you call it without toString() you will get an error: "substr is not a function". The description from the function you can see under https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/String/substring. getFullYear() method is an absolute number, and you have to convert it to string, in order to get a substring. – TeslaXba Oct 15 '19 at 07:49
1

getYear returns the year minus 1900 like described here

you maybe want to use getFullYear()

already answered by: how to get 2 digit year

Manfred Wippel
  • 1,946
  • 1
  • 15
  • 14
1

Here is the answer

var today = new Date();
var dd = String(today.getDate());
var mm = String(today.getMonth() + 1);
var yy = today.getFullYear().toString().substr(-2);
var dateToday = dd+"-"+mm+"-"+yy;
console.log(dateToday);
bhuvnesh pattnaik
  • 1,365
  • 7
  • 14
0

getYear() is no longer used and it has been replaced by getFullYear().The getYear method returns the year minus 1900.

In Your case the the year 2019 is getting substracted by 1900 so it is showing 119.

var today = new Date();
var dd = String(today.getDate());
var mm = String(today.getMonth() + 1);
var yy = today.getFullYear();
var dateToday = dd+"-"+mm+"-"+yy;
var dateformat = dateToday.replace("2019","19")
console.log(dateformat);