===== 日時 =====
==== 日時取得 ====
=== Dateクラス ===
import java.util.Date;
import java.text.SimpleDateFormat;
・・・
Date now = new Date();
System.out.println(now);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy'/'MM'/'dd' 'HH':'mm':'ss");
System.out.println(sdf.format(now));
Sun Jun 10 15:16:09 JST 2018
2018/06/10 15:16:09
=== Instantクラス、ZonedDateTimeクラス ===
※Java8以降
import java.time.*;
・・・
Instant i = Instant.now();
ZonedDateTime z1 = i.atZone(ZoneId.of("Asia/Tokyo"));
ZonedDateTime z2 = ZonedDateTime.now();
System.out.println(z1);
System.out.println(z2);
2018-06-10T22:33:08.600+09:00[Asia/Tokyo]
2018-06-10T22:33:08.728+09:00[Asia/Tokyo]
=== LocalDateTimeクラス ===
※Java8以降
import java.time.*;
・・・
LocalDateTime t = LocalDateTime.now();
System.out.println(t);
2018-06-10T22:36:11.303
==== 時刻を表すクラスと保持情報 ====
※Java8以降
^ クラス ^ 情報 |||||
| ::: ^ 年 ^ 月 ^ 日 ^ 時刻 ^ ゾーン ^
| ZonedDateTime | 〇 | 〇 | 〇 | 〇 | 〇 |
| LocalDateTime | 〇 | 〇 | 〇 | 〇 | - |
| LocalDate | 〇 | 〇 | 〇 | - | - |
| LocalTime | - | - | - | 〇 | - |
| Year | 〇 | - | - | - | - |
| YearMonth | 〇 | 〇 | - | - | - |
| Month | - | 〇 | - | - | - |
| MonthDay | - | 〇 | 〇 | - | - |
==== 時間の計算 ====
=== Periodクラス ===
import java.time.*;
import java.time.format.*
・・・
LocalDate from = LocalDate.of(2017, 4, 1);
LocalDate to = LocalDate.of(2018, 6, 10);
Period period = Period.between(from, to);
System.out.println(period);
System.out.println(period.getYears());
System.out.println(period.getMonths());
System.out.println(period.getDays());
System.out.println(period.toTotalMonths());
P1Y2M9D ※1年2か月9日の意味
1
2
9
14
=== Durationクラス ===
import java.time.*;
・・・
LocalDateTime from = LocalDateTime.of(2018, 6, 10, 10, 0, 0);
LocalDateTime to = LocalDateTime.of(2018, 6, 10, 23, 59, 59);
Duration duration = Duration.between(from, to);
System.out.println(duration);
System.out.println(duration.toDays());
System.out.println(duration.toHours());
System.out.println(duration.toMinutes());
System.out.println(duration.getSeconds());
PT13H59M59S ※13時間59分59秒という意味
0
13
839
50399