1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScriptで前年の1月1日と12月31日を文字列で使いたかった

Last updated at Posted at 2018-11-22
var start = (today.getYear() - 1 + 1900).toString() + '-01-01'; // 前年の1月1日 e.g. 2017-01-01
var end   = (today.getYear() - 1 + 1900).toString()+ '-12-31'; // 前年の12月31日 e.g. 2017-12-31

console.log(start); // 2017-01-01
console.log(end); // 2017-12-31

JavaScriptで日付を扱う場合にはDateを使う。
ただDategetYear()は1900年からの差分を戻してくるため、足してやる必要がある。

For years greater than or equal to 2000, the value returned by getYear() is 100 or greater. For example, if the year is 2026, getYear() returns 126.
For years between and including 1900 and 1999, the value returned by getYear() is between 0 and 99. For example, if the year is 1976, getYear() returns 76.
For years less than 1900, the value returned by getYear() is less than 0. For example, if the year is 1800, getYear() returns -100.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getYear

ちなみに1900年以前、例えば1800年とかだと-100が戻るらしい。なるほど。

でもなぜ1900年が基準なんだろう…。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?