7
6

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.

Javaにおける日付の整形について

Last updated at Posted at 2016-02-14

日付を扱う場合、想定していなかった
動きとなりましたので、記載しておきます。

Androidアプリを作成していて、サーバサイド側からJSONの形で
日付情報を受け取り、整形しようとしたとき実行時例外が発生しました。

処理概要
1.Androidアプリから、サーバサイドにGETリクエスト送付
2.サーバサイドからJSONの形でレスポンスを送付
3.Androidアプリでレスポンスを受け取って以下処理
 a.日付をString型→Date型に変換
 b.Date型→String型に変換(フォーマット整形)
4.Androidの画面上に日付表示

3-a、3-bの処理だけ抜粋
入力するデータ:2016-02-14T12:41:57.000Z
出力したいデータ:2016/02/14 12:41

NGケース

jikan.java
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date formatDate = sdf.parse(jsonObject.getString("created_at"));
SimpleDateFormat format2 = new SimpleDateFormat("yyyy/MM/dd HH:mm");
String format_after = format2.format(formatDate);
Log.d("debug",format_after) // sdf.parse()で、java.text.ParseException

修正箇所

before SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
after  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

以下のページによると、日付のフォーマットはW3Cで表記法が制定されていて、合計6種類あるそうです。Java内部の動き含めて、もう少し勉強したいと思います。

(参考)日付の表記に関するノート
http://www.kanzaki.com/docs/html/dtf.html

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?