※当サイトの記事には、広告・プロモーションが含まれます。

Java 8 で導入されたTimeパッケージのAPIで、24時間超過の判定をしてみる

CTU、こちらジャック・バウアー。問題発生だ」

海外ドラマ「24」の名台詞が出たところで、今回は、Javaの話です。ちなみに、「24」は観たことありません...

というわけで、レッツトライ。

24時間超過の判定がしたいんじゃ~

時間は待っちゃくれない、紅の豚、豚をぶたないで~、ということで、時間に追われた現代人である我々は、24時間という1日を生きている訳で、24時間が経過したかどうかってこと、知りたいあるあるだよね~、え?、ないですか?

というわけで、Java 8 のTimeパッケージ にて24時間超過の判定をしてみたのです。

m-shige1979.hatenablog.com

⇧  上記サイト様を参考にさせていただきました。

 

Eclipseを起動し、「ファイル(F)」>「新規(N)」>「Java プロジェクト」で。

f:id:ts0818:20181201222320p:plain

適当に、プロジェクトを作成したらば、適当に「クラス」ファイルを作成。

f:id:ts0818:20181201222109p:plain

クラスファイルを編集で。 

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class Test24 {

	public static String FORMAT = "yyyy-MM-dd HH:mm:ss";

	public static void main(String[] args) {
		//
		LocalDateTime systemTime;
		LocalDateTime tradeTime;

		// 取引が行われた日付時刻を想定
		String tradeTimeStr = "2018-11-30 17:18:26";

		DateTimeFormatter dateFormat = formatDate(FORMAT);
		systemTime = parse(dateFormat.format(LocalDateTime.now()), dateFormat);
		tradeTime = parse(tradeTimeStr, dateFormat);

		System.out.println(systemTime);
		System.out.println(tradeTime);

		// 秒計算
		long localDiffDays = ChronoUnit.SECONDS.between(tradeTime, systemTime);
		System.out.println("秒 :" + localDiffDays);

		// 24時間
		Long oneDayTime = 86400L;

		Long dayTimeOverJudge;
		Boolean result = false;

		// 24時間超過判定
		if(localDiffDays - oneDayTime > 0) {
			result = true;
		}
		System.out.println(result);

	}

	// 文字列の日付のフォーマットを整形
	public static LocalDateTime parse(String date, DateTimeFormatter format) {
		return LocalDateTime.parse(date, format);
	}

    // フォーマットの雛形を作成
	public static DateTimeFormatter formatDate(String format) {
		return DateTimeFormatter.ofPattern(format);
	}

}

で、保存して、実行してみます。

f:id:ts0818:20181201222858p:plain

実行時刻「2018/12/01 22:30:42」と取引時刻「2018/11/30 17:18:26」を比較すると、24時間が経過してることが判定されました。

f:id:ts0818:20181201223230p:plain

⇧  未来日(現在時刻より先、つまり、現在時刻が、「2018/12/01 22:50:30」とかだったら、未来日は「2018/12/01 22:50:31」とかのこと。未だ来てない日ということで、未来日ということらしい)とかの考慮は一切されていませんが。

 

TimeパッケージのAPIにも慣れていかねばという感じですかね。どうも、Java 8で新規に追加された機能には懐疑的ですが。例えば、ラムダ式が例外との相性最悪とか...

Timeパッケージも爆弾を抱えているんじゃなかろうかという気分ですが。

今回はこのへんで。