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 5 years have passed since last update.

【Java】Dateクラスでミリ秒を使って10日後の日付情報を取得する

Last updated at Posted at 2020-10-11

Dateクラスの扱いの練習

Dateについて勉強していましたが、

  • エポックミリ秒についての理解
  • 形式を指定して表示する方法

この2点においてあんまりちゃんと理解できていない部分があった感じがするのでまとめます。

本当はCalendarクラスのフィールドがよくわかっていないことで沼ってたというのもあるし、Java8からは新しい日付APIがありもう少し直感に近い扱いができるらしいですが、それについてもしっかり原始的なDateクラスの理解を始めた方がいいと感じたので、自分なりにいろいろ検証しつつ描いてみました。

Calendarクラスを使ったバージョンも参考になれば

Dateクラスを使って10日後の日付情報を表示してみよう

TenDaysDate.java
import java.text.SimpleDateFormat;
import java.util.Date;

public class TenDaysDate {

	public static void main(String[] args) {
		
		// Date型のlong値を変更して10日後の日付を取得
		Date d = new Date();									// 現在の日時を取得
		long ts = System.currentTimeMillis(); // 現在のエポックミリ秒を取得
		
		// Date型のgetTimeメソッドの返り値とcurrentTimeMillisの値を比較
		System.out.println("d.getTime:\t\t\t" + d.getTime());				// Date.getTimeの値
		System.out.println("currentTimeMillis:\t" + ts);						// currentTimeMillisの値
		if(ts == d.getTime()) System.out.println("いっしょやん");			// long値は一致します
		
		// Date型の日付情報を形式を指定して表示
		SimpleDateFormat f = new SimpleDateFormat("yyyy年MM月dd日"); // 表示形式を指定
		System.out.println("今日の日付:\t" + f.format(d));						// SimpleDateFormat型にDate型の引数を渡す
		
		// Date型のsetTimeメソッドで10日分のミリ秒を加算して10日後の日付情報に変更する
		d.setTime(d.getTime() + (long)(24 * 60 * 60 * 1000) * 10);	// ()が1日のミリ秒
		System.out.println("10日後の日付:\t" + f.format(d));					// SimpleDateFormat型にDate型の引数に渡す
	}

}

出力結果
d.getTime:			1602415769204
currentTimeMillis:	1602415769204
いっしょやん
今日の日付:	2020年10月11日
10日後の日付:	2020年10月21日

getとset


d.getTime(); // エポックミリ秒が返ってくる
d.setTime(エポックミリ秒); // エポックミリ秒を引数に渡して日付情報をセットする

エポックミリ秒

1970年1月1日0時0分0秒UTCからの経過ミリ秒
Unix Timeともいう
1日分のミリ秒は24 * 60 * 60 * 1000。これに10をかければ10日分のミリ秒になる。

また、getTime() + 24 * 60 * 60 * 1000 * 10とすることで、現在時刻よりさらに10日分のミリ秒経過後の日付情報を取得できる。

場合によっては(long)24 * 60 * 60 * 1000としてlong型にキャストする必要あり?

うるい年などによって思った日付にならないこともある

10年後とかそういう中に閏年が出てくると、1年後のミリ秒として24 * 60 * 60 * 1000 * 365 * 10という風にしても、10年後の同じ月同じ日にならない。

長いスパンで計算するときは年フィールドなどに加算して計算しないといけませんね。ややこしい。

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?