Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sample of Java8 time library
package com.orb.framework;
import static java.time.format.DateTimeFormatter.ofPattern;
import static org.junit.Assert.fail;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.DateTimeParseException;
import org.junit.Test;
public class InstantTest {
@Test
public void instantTest() {
Instant i1 = LocalDateTime.of(2018,5,1,11,11,11,100000000).toInstant(ZoneOffset.UTC);
Instant i2 = LocalDateTime.of(2018,5,1,11,11,11,0).toInstant(ZoneOffset.UTC);
Instant i3 = LocalDateTime.of(2018,5,1,11,11,0,0).toInstant(ZoneOffset.UTC);
Instant i4 = LocalDateTime.of(2018,5,1,11,0,0,0).toInstant(ZoneOffset.UTC);
Instant i5 = LocalDateTime.of(2018,5,1,0,0,0,0).toInstant(ZoneOffset.UTC);
System.out.println(i1);
System.out.println(i2);
System.out.println(i3);
System.out.println(i4);
System.out.println(i5);
System.out.println("==== toString ====");
System.out.println(i1.toString());
System.out.println(i2.toString());
System.out.println(i3.toString());
System.out.println(i4.toString());
System.out.println(i5.toString());
}
@Test
public void formatterTest2() {
DateTimeFormatter formatter = ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
assertFormat("2018-04-12T08:49:07Z", formatter, ZoneOffset.UTC);
}
@Test
public void formatterTest5() {
DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder()
.append(ofPattern("yyyy-MM-dd'T'HH:mm:ss"))
.appendOptional(ofPattern(".SSS"))
.appendOptional(ofPattern("'Z'"));
DateTimeFormatter formatter = builder.toFormatter();
assertFormat("2018-04-12T08:49:07Z", formatter, ZoneId.of("Asia/Tokyo"));
assertFormat("2018-04-12T08:49:07.237Z", formatter, ZoneId.of("Asia/Tokyo"));
}
@Test
public void expressionTest() {
// for (String z : ZoneId.getAvailableZoneIds()) {
// System.out.println(z);
// }
ZonedDateTime znow = ZonedDateTime.now(ZoneId.of("Asia/Tokyo"));
System.out.println(DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss").format(znow));
//znow = ZonedDateTime.now(ZoneOffset.UTC);
znow = ZonedDateTime.now(ZoneId.of("UTC"));
System.out.println(DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss").format(znow));
}
public void assertFormat(String raw, DateTimeFormatter formatter, ZoneId zone) {
try {
LocalDateTime localDate = LocalDateTime.parse(raw, formatter);
ZonedDateTime zLocalDate = ZonedDateTime.of(localDate, zone);
} catch (DateTimeParseException e) {
e.printStackTrace();
fail();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment