23
20

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

Javaで日付と時刻を扱う

Last updated at Posted at 2016-02-09

java.time.LocalDateTime(java8)

  • LocalDateTime now = LocalDateTime.now();
  • LocalDateTime ymd = LocalDateTime.of(2016, 1, 1, 0, 0);
  • LocalDateTime ymdhms = LocalDateTime.of(2016, 1, 1, 23, 59, 59);
  • int year = ymd.getYear();
  • int month = ymd.getMonth().getValue();
  • int date = ymd.getDayOfMonth();
  • DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:flag_mm:ss");
  • dtf.format(ymdms);
  • Java8の日時APIはとりあえずこれだけ覚えとけ」が参考になる

(java7なら)Joda-Time

java.util.Date(できれば使わない)

  • 日時データを保持するだけのクラス
  • このクラスから直接「年月日」を取得するメソッドは既に非推奨となっている。
  • 書式を整えるにはDateFormatクラスを使う
SimpleDateFormat sdf = new SimpleDateFormat("kk:mm");
// 11:30以前の場合
if (sdf.parse(data.get(1)).compareTo(sdf.parse("11:30")) <= 0) {
  System.out.println("お昼前だよ");
}
  • Calendar型に変換

    • cal.setTime(date);
  • BigDecimal型のUTCをもとにDate型を作成

    • BigDecimal utc = (BigDecimal) array.get(0);
    • Date day = new Date(utc.longValue());
  • java.sql.Dateに変換する

           public static java.sql.Date toSqlDate(java.util.Date date) {
               return new java.sql.Date(date.getTime());
           }

java.util.Calendar(できれば使わない)

  • 月は0~11
  • Calendar cal = Calendar.getInstance();
  • cal.set(2015,11,31, 0, 0, 0); // 2015/12/31 am0:00
  • cal.setTimeZone(TimeZone.getTimeZone("Asia/Tokyo"));
  • int year = cal.get(Calendar.YEAR);
  • int month = cal.get(Calendar.MONTH) - 1;
  • int date = cal.get(Calendar.DATE);
  • cal.add(Calendar.DAY_OF_MONTH, 1); // 1日加算
  • cal.add(Calendar.DAY_OF_MONTH, -2); // 2日減算
  • cal.add(Calendar.MONTH, 1); // 1か月加算
  • cal.add(Calendar.YEAR, -1); // 1年減算
  • Dateに変換
    • Date date = cal.getTime();
  • java.text.SimpleDateFormat
    • SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:flag_mm:ss");
    • sdf.format(cal.getTime());

時刻を扱う

プログラムの実行時間をはかる

org.apache.commons

build.gradle
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.10'
StopWatch stopWatch = new StopWatch();

// 計測開始
stopWatch.start();

Thread.sleep(500);

// 計測停止
stopWatch.stop();

// 経過時間出力
System.out.println(stopWatch.getTime()); // ⇒500

org.springframework.util.StopWatch

StopWatch stopWatch = new StopWatch();
stopWatch.start();
// ... more
stopWatch.stop();
System.out.println(stopWatch.getTotalTimeMillis());
System.out.println(stopWatch.prettyPrint());

プレーン

	// 全体の「時間:分:秒」
	 private String formatedTimeV2(long millis) {
	        return String.format("%02d:%02d:%02d", 
	                TimeUnit.MILLISECONDS.toHours(millis),
	                TimeUnit.MILLISECONDS.toMinutes(millis) - 
	                TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
	                TimeUnit.MILLISECONDS.toSeconds(millis) - 
	                TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
	         );
	 }
	// 個別の「分 min, 秒 sec」
	private String formatedTime(long millis) {
		return String.format("%d min, %d sec", 
			    TimeUnit.MILLISECONDS.toMinutes(millis),
			    TimeUnit.MILLISECONDS.toSeconds(millis) - 
			    TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
			);
	}

	@Test
	public void formatTime() throws InterruptedException {
		long start = System.currentTimeMillis();
		Thread.sleep(1000);
		long end = System.currentTimeMillis();
		System.out.println(formatedTime(end - start));
	}

結果

0 min, 1 sec
23
20
2

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
23
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?