Java 8新しい日時ライブラリjava.timeの使用例
例1どのようにしてJava 8で当日の日付を取得しますか?
LocalDate today = LocalDate.now();
System.out.println("Today's Local date : " + today);
Output
Today's Local date : 2020-01-14
例2 Java 8で現在の年月日をどうやって取得しますか?
LocalDate today = LocalDate.now();
int year = today.getYear();
int month = today.getMonthValue();
int day = today.getDayOfMonth();
System.out.printf("Year : %d Month : %d day : %d \t %n", year, month, day);
Output
Today's Local date : 2020-01-14
Year : 2020 Month : 1 day : 14
例3 Java 8における特定の日付の取得方法
LocalDate dateOfBirth = LocalDate.of(2010, 01, 14);
System.out.println("Your Date of birth is : " + dateOfBirth);
Output : Your Date of birth is : 2010-01-14
例4 Java 8では、2つの日付が等しいかどうかをどうチェックしますか?
LocalDate date1 = LocalDate.of(2020, 01, 14); if(date1.equals(today)){
System.out.printf("Today %s and date1 %s are same date %n", today, date1);
}
Output
today 2020-01-14 and date1 2020-01-14 are same date
例5 Java 8では、誕生日などの重複イベントをどのようにチェックしますか?
LocalDate dateOfBirth = LocalDate.of(2010, 01, 14);
MonthDay birthday = MonthDay.of(dateOfBirth.getMonth(), dateOfBirth.getDayOfMonth());
MonthDay currentMonthDay = MonthDay.from(today);
if(currentMonthDay.equals(birthday)){
System.out.println("Many Many happy returns of the day !!");
}else{
System.out.println("Sorry, today is not your birthday");
}
Output: Many Many happy returns of the day !!
例6どのようにしてJava 8で現在の時間を取得しますか?
LocalTime time = LocalTime.now();
System.out.println("local time now : " + time);
Output
local time now : 16:33:33.369 // in hour, minutes, seconds, nano seconds
例7時間の中の時間を増やすにはどうすればいいですか?
LocalTime time = LocalTime.now();
LocalTime newTime = time.plusHours(2); // adding two hours
System.out.println("Time after 2 hours : " + newTime);
Output :
Time after 2 hours : 18:33:33.369
例8どうやって1週間後の日付を取得しますか?
LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS);
System.out.println("Today is : " + today);
System.out.println("Date after 1 week : " + nextWeek);
Output:
Today is : 2020-01-14
Date after 1 week : 2020-01-21
例9年前後の日付
LocalDate previousYear = today.minus(1, ChronoUnit.YEARS);
System.out.println("Date before 1 year : " + previousYear);
LocalDate nextYear = today.plus(1, YEARS);
System.out.println("Date after 1 year : " + nextYear);
Output:
Date before 1 year : 2019-01-14
Date after 1 year : 2021-01-14
例10は、Java 8でクロックを使用する。
// Returns the current time based on your system clock and set to UTC.
Clock clock = Clock.systemUTC();
System.out.println("Clock : " + clock);
// Returns time based on system clock zone Clock defaultClock =
Clock.systemDefaultZone();
System.out.println("Clock : " + clock);
Output:
Clock : SystemClock[Z]
Clock : SystemClock[Z]
public class MyClass {
private Clock clock; // dependency inject ...
public void process(LocalDate eventDate) {
if(eventDate.isBefore(LocalDate.now(clock)) {
...
}
}
}
例11 Javaでは、ある日付が他の日付の前かそれとも後かをどう判断しますか?
LocalDate tomorrow = LocalDate.of(2020, 1, 15);
if(tommorow.isAfter(today)){
System.out.println("Tomorrow comes after today");
}
LocalDate yesterday = today.minus(1, DAYS);
if(yesterday.isBefore(today)){
System.out.println("Yesterday is day before today");
}
Output:
Tomorrow comes after today
Yesterday is day before today
例12は、Java 8で異なるタイムゾーンを処理する。
// Date and time with timezone in Java 8 ZoneId america = ZoneId.of("America/New_York");
LocalDateTime localtDateAndTime = LocalDateTime.now();
ZonedDateTime dateAndTimeInNewYork = ZonedDateTime.of(localtDateAndTime, america );
System.out.println("Current date and time in a particular timezone : " + dateAndTimeInNewYork);
Output :
Current date and time in a particular timezone : 2020-01-14T16:33:33.373-05:00[America/New_York]
Exception in thread "main" java.time.zone.ZoneRulesException: Unknown time-zone ID: ASIA/Tokyo
at java.time.zone.ZoneRulesProvider.getProvider(ZoneRulesProvider.java:272)
at java.time.zone.ZoneRulesProvider.getRules(ZoneRulesProvider.java:227)
at java.time.ZoneRegion.ofId(ZoneRegion.java:120)
at java.time.ZoneId.of(ZoneId.java:403)
at java.time.ZoneId.of(ZoneId.java:351)
例13どのように固定の日付を表しますか?例えば、クレジットカードの期限が切れる時間。
YearMonth currentYearMonth = YearMonth.now();
System.out.printf("Days in month year %s: %d%n", currentYearMonth, currentYearMonth.lengthOfMonth());
YearMonth creditCardExpiry = YearMonth.of(2018, Month.FEBRUARY);
System.out.printf("Your credit card expires on %s %n", creditCardExpiry);
Output:
Days in month year 2020-01: 31
Your credit card expires on 2018-02
例14はどのようにJava 8で閏年を検査しますか?
if(today.isLeapYear()){
System.out.println("This year is Leap year");
}else {
System.out.println("2020 is not a Leap year");
}
Output: 2020 is not a Leap year
例15二つの日付の間に何日間、何ヶ月が含まれていますか?
LocalDate java8Release = LocalDate.of(2020, Month.MARCH, 14);
Period periodToNextJavaRelease = Period.between(today, java8Release);
System.out.println("Months left between today and Java 8 release : " + periodToNextJavaRelease.getMonths() );
Output:
Months left between today and Java 8 release : 2
例16タイムゾーンオフセットの日付と時間
LocalDateTime datetime = LocalDateTime.of(2020, Month.JANUARY, 14, 19, 30);
ZoneOffset offset = ZoneOffset.of("+05:30");
OffsetDateTime date = OffsetDateTime.of(datetime, offset);
System.out.println("Date and Time with timezone offset in Java : " + date);
Output :
Date and Time with timezone offset in Java : 2020-01-14T19:30+05:30
例17 Java 8で現在のタイムスタンプの取得方法
Instant timestamp = Instant.now();
System.out.println("What is value of this instant " + timestamp);
Output :
What is value of this instant 2020-01-14T08:33:33.379Z
例18どのようにしてJava 8に予め定義されたフォーマット器を使用して日付を解析/フォーマットするか?
String dayAfterTommorrow = "20200116";
LocalDate formatted = LocalDate.parse(dayAfterTommorrow,
DateTimeFormatter.BASIC_ISO_DATE);
System.out.printf("Date generated from String %s is %s %n", dayAfterTommorrow, formatted);
Output :
Date generated from String 20200116 is 2020-01-16
例19どのようにJavaでカスタムフォーマットを使って日付を解析しますか?
String goodFriday = "Apr 18 2020";
try {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd yyyy");
LocalDate holiday = LocalDate.parse(goodFriday, formatter);
System.out.printf("Successfully parsed String %s, date is %s%n", goodFriday, holiday);
} catch (DateTimeParseException ex) {
System.out.printf("%s is not parsable!%n", goodFriday);
ex.printStackTrace();
}
Output :
Successfully parsed String Apr 18 2020, date is 2020-04-18
例20はどのようにしてJava 8で日付をフォーマットし、文字列に変換しますか?
LocalDateTime arrivalDate = LocalDateTime.now();
try {
DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM dd yyyy hh:mm a");
String landing = arrivalDate.format(format);
System.out.printf("Arriving at : %s %n", landing);
} catch (DateTimeException ex) {
System.out.printf("%s can't be formatted!%n", arrivalDate);
ex.printStackTrace();
}
Output : Arriving at : Jan 14 2020 04:33 PM
例21はタイムスタンプ秒とミリ秒を取得する。
Instant ins= Instant.now();
System.out.println("10 "+ins.getEpochSecond());
System.out.println("13 "+ins.toEpochMilli());
Java 8における日付と時間APIのいくつかの重要な点ここで、Java 8の新しい日時ライブラリjava.timeに関する記事を紹介します。Java 8の新しい日時ライブラリjava.timeの内容については、以前の文章を検索してください。または下記の関連記事を引き続きご覧ください。これからもよろしくお願いします。