GetFullYear returns a year earlier on the first day of the year

I try to deduce only a year from the date, but for some reason on the first day of the year he was returning to the previous year.

new Date('2012-01-01').getFullYear()

will return '2011' and

new Date('2012-01-02').getFullYear()

will return '2012'

Any good ideas on what I'm doing wrong? or a fix for this would be helpful.

+4
source share
3 answers

new Date('2012-01-01')will analyze the date assuming it in UTC. The created object Dateincludes your time zone, so it takes this into account when printing the result getYear(). If you are in GMT-nothing, then you are returning to the previous year. You can ignore time slots and handle only UTC by calling Date.prototype.getUTCFullYear().

+6

new Date(dateString) , . , :

new Date('2012-01-01T00:00:00').getFullYear();

:

function dateFromString(dateString){
  return new Date(dateString+'T00:00:00');
}
console.log(dateFromString('2012-01-01').getFullYear());
0

, , "2012-01-01", GMT 00:00:00. , , , , 31 .

, , Date ( Date.parse, ), . ISO 8601 ISO. , ECMAScript ed 3 (IE 8 ). ES5 , UTC ( ISO). ECMAScript 2015, , , , TC39 , UTC, ( - , ).

So, if you want consistency, manually enter the date strings, for example. to treat the ISO 8601 date as local, use a function such as:

/*  Parse ISO 8601 date string without time zone
**  as a local date
**  @param {string} s - date string to parse in format yyyy-mm-dd
**  @returns {Date}   - local Date, or invalid date if any value is
**                      out of range
*/
function parseISOLocal(s) {
  var b = s.split(/\D/);
  var d = new Date(b[0], --b[1], b[2]);
  return d && d.getMonth() == b[1]? d : new Date(NaN);
}

var s = '2012-01-01';

document.write(parseISOLocal(s))
Run codeHide result
0
source

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


All Articles