1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

日付でソートするとき

Posted at

はじめに

文字列型でソートするよりDateTime型でソートする方が良いというお話。

なぜなのか

①正確なソート
文字列型でソートすると、アルファベット順でソートされる
2024-10-01と2024-2-01を文字列型でソートすると、2024-10-01が先に来てしまい、想定通りの結果にならない。

②一貫性
文字列型の日付はフォーマットが統一されていないと正しくソートできない。
例えば、"2024/10/01"と"2024-10-01"は異なる形式のため、正しくソートされない。
DateTime型は内部的に一貫した形式で保持されるため、フォーマットの違いによる問題は発生しない。

終わりに

APIなどで、日付が入っているものについては、DateTime型に変換するなどをして対応する。
もしかしたら、APIで日付ソートが入っている場合は、アプリ側で気にしなくて良いが、もしAPI側で考慮が漏れていたら気をつけよう。

1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?