0
var a = new Date("19-06-2018");
var b = new Date("19-07-2018");
var c = a.getTime();
var d = b.getTime();

e = new Date(c);
e.getYear();

O/p: 2019

While working with sorting of date in javascript,I came across that in the above code segment for date operations,when I convert date string to date object and get the time and get back the year using date object I m getting different yeari.e 2019 instead of 2018.How is this possible?

Gunacelan M
  • 179
  • 2
  • 10
  • 1
    I get NaN, because browser - but if I use a valid date string, I get `118` because that is 1900 + 118 = 2018 (by the way, you seem to be using *Internet Explorer* - why?) but even IE outputs **119** not **2019** - so I'm guessing your question is made up code – Jaromanda X Jul 25 '18 at 05:34
  • From Mozilla docs: "Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local." – Jack Ryan Jul 25 '18 at 05:39
  • I'm working with test complete tool – Gunacelan M Jul 25 '18 at 05:53

2 Answers2

0

Using .getYear() is only going to return from 0-100 in between years 1900 to 2000. When below the 1900s, it will return negative integers and above 2000 it returns numbers higher than 100 + years from year 2000. i.e. 2026 = 126 because it's 126 years after the year 1900.

I think you want to use e.getFullYear() to return the year from your variable.

Check this link out: MDN - getYear()

Hope that helps! :D

P.S. I am not sure why your getting 2019, I tried it out in a codepen and didn't see those results.

Anirudha Gupta
  • 9,073
  • 9
  • 54
  • 79
matt6frey
  • 133
  • 10
0

the way you are declaring the date is returning null, as you can see in console.log.

here is the Date documentation - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

And it uses getFullYear instead of getYear. As matt6frey said the getYear is deprecated.

console.log(new Date("19-06-2018"));

var a = new Date("2018-06-19");
var c = a.getTime();
var e = new Date(c);


console.log(e.getFullYear())
martinho
  • 1,006
  • 1
  • 10
  • 24
  • "*the way you are declaring the date is returning null*". It should not, it should return a Date object, either with a valid (but possibly incorrect) time value or NaN, representing an invalid date. *getYear* is not deprecated in web browsers, they are required to continue to support it even in the latest draft. – RobG Jul 25 '18 at 12:33