0
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 1 year has passed since last update.

JavaScriptで記事日付を年度別でソートして表示する

Posted at

誰かが実装してそうなものですが、意外と調べても見つからなかったので。

デモ

See the Pen Order By Financial Year by qwe001 (@qwe001) on CodePen.

実装

要は、記事の投稿月が1~3月の時は
1年引いた年別グループに格納すればOKってことです

var dates = [
  {"date":"2021-03-31"},
  {"date":"2021-04-01"},
  {"date":"2022-03-31"},
  {"date":"2022-04-01"}
];

var years = {};
for(var i in dates){
  var date = dates[i].date;

  var m = moment(date);
  var ymd = m.format('YYYY-MM-DD');
  var year = parseInt(m.format('YYYY'), 10);
  var month = parseInt(m.format('M'), 10);

  if(month <= 3){
    year = m.subtract(1, 'year').format('YYYY');
    year = parseInt(year, 10);
  }

  if(years.hasOwnProperty(year) === false){
    years[year] = [];
  }

  years[year].push(ymd);
}

console.log(years);
{
  "2020" : [
    "2021-03-31"
  ],
  "2021" : [
    "2021-04-01",
    "2022-03-31"
  ],
  "2022" : [
    "2022-04-01"
  ]
}
0
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
0
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?