Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
http://bufferings.hatenablog.com/entry/2017/10/23/000057 (assertjの3.8.0を使ってます)
package com.example.demo;
import org.junit.Test;
import java.time.LocalDate;
import java.time.chrono.JapaneseDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.format.ResolverStyle;
import java.util.Locale;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
public class DateAndTimeTest {
@Test
public void 普通にyyyyとuuuuを使ったら同じ結果になる() {
LocalDate target = LocalDate.of(2017, 10, 22);
assertThat(target.format(DateTimeFormatter.ofPattern("yyyy/MM/dd", Locale.US)))
.isEqualTo("2017/10/22");
assertThat(target.format(DateTimeFormatter.ofPattern("uuuu/MM/dd", Locale.US)))
.isEqualTo("2017/10/22");
}
@Test
public void Gをつけてみたらどうなる() {
LocalDate target = LocalDate.of(2017, 10, 22);
assertThat(target.format(DateTimeFormatter.ofPattern("G yyyy/MM/dd", Locale.US)))
.isEqualTo("AD 2017/10/22");
assertThat(target.format(DateTimeFormatter.ofPattern("G uuuu/MM/dd", Locale.US)))
.isEqualTo("AD 2017/10/22");
}
@Test
public void 紀元前を渡したらどうなる() {
LocalDate target = LocalDate.of(-2017, 10, 22);
assertThat(target.format(DateTimeFormatter.ofPattern("G yyyy/MM/dd", Locale.US)))
.isEqualTo("BC 2018/10/22");
assertThat(target.format(DateTimeFormatter.ofPattern("G uuuu/MM/dd", Locale.US)))
.isEqualTo("BC -2017/10/22");
}
@Test
public void こういう風に使うってことか() {
LocalDate target = LocalDate.of(2017, 10, 22);
assertThat(target.format(DateTimeFormatter.ofPattern("G yyyy/MM/dd", Locale.US)))
.as("yyyy使うなら暦と一緒に")
.isEqualTo("AD 2017/10/22");
assertThat(target.format(DateTimeFormatter.ofPattern("uuuu/MM/dd", Locale.US)))
.as("uuuu使うなら暦は使わない")
.isEqualTo("2017/10/22");
}
@Test
public void 和暦はこうなるってことか() {
JapaneseDate japaneseDate = JapaneseDate.of(2017, 10, 22);
assertThat(japaneseDate.format(DateTimeFormatter.ofPattern("G yyyy/MM/dd", Locale.JAPAN)))
.isEqualTo("平成 0029/10/22");
assertThat(japaneseDate.format(DateTimeFormatter.ofPattern("uuuu/MM/dd", Locale.JAPAN)))
.isEqualTo("2017/10/22");
}
@Test
public void STRICTモードで暦指定なしyyyyは例外発生() {
assertThatExceptionOfType(DateTimeParseException.class)
.isThrownBy(() -> LocalDate.parse("2017/10/22", DateTimeFormatter.ofPattern("yyyy/MM/dd")
.withResolverStyle(ResolverStyle.STRICT)));
}
@Test
public void yyyyを使うなら暦を指定する() {
assertThat(LocalDate.parse("AD 2017/10/22",
DateTimeFormatter.ofPattern("G yyyy/MM/dd").withResolverStyle(ResolverStyle.STRICT)))
.isEqualTo(LocalDate.of(2017, 10, 22));
}
@Test
public void でも西暦を扱うときには暦を指定したりしないだろうからuuuuを使うべきってことね() {
assertThat(LocalDate.parse("2017/10/22",
DateTimeFormatter.ofPattern("uuuu/MM/dd").withResolverStyle(ResolverStyle.STRICT)))
.isEqualTo(LocalDate.of(2017, 10, 22));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment