Why is my parsing not correct?

I am having problems sharing dates after 01/01/2000. Results are returned incorrectly. 1999 is analyzed as 1999, when it comes to 2000, it analyzes it as 0100, and then 2001 as 0101, etc. Here is sample code to illustrate this problem:

<script type="text/javascript" language="javascript">


// functions incorrect  changes year from 2010 to 0101
var d = (new Date("12/01/2009"));
if (d.getMonth() < 11) 
 { d = new Date(d.getYear(), d.getMonth() + 1, 1); } 
 else
 { d = new Date(d.getYear() + 1, 0, 1); } 
document.write(d);
//  Result:  Sat Jan 01 0101 00:00:00 GMT-0500 (Eastern Standard Time) 

document.write('<br />');


document.write(Date.parse(Date()) < Date.parse(d));
// 
// Result: false  today should definitely be < 01/01/2010


document.write('<br />');


// Functions correctly if year is before 2000

var d = (new Date("12/01/1998"));

if (d.getMonth() < 11) 
 { d = new Date(d.getYear(), d.getMonth() + 1, 1); } 
 else
 { d = new Date(d.getYear() + 1, 0, 1); } 


document.write(d);
//  Result:  Fri Jan 01 1999 00:00:00 GMT-0500 (Eastern Standard Time)  
document.write('<br />');


document.write(Date.parse(Date()) < Date.parse(d));
// false


</script>
+3
source share
3 answers

You need to use d.getFullYear () instead of d.getYear ()

getYear () gives only the number of years since 1900, obviously;)

+5
source

Date.parse(). , , , new Date("12/01/2009") . , Date.parse() , . :

var d = new Date(Date.parse("12/01/2009"));

, getFullYear(), getYear(), , , .

+2

what getYear () returns is browser dependent. Instead, try d.getFullYear ().

Useful Javascript link: http://www.w3schools.com/jsref/jsref_obj_date.asp

0
source

Source: https://habr.com/ru/post/1704744/


All Articles