Skip to content

Instantly share code, notes, and snippets.

@mundry
Last active August 29, 2015 14:02
Show Gist options
  • Save mundry/42daf18c653708d42d5d to your computer and use it in GitHub Desktop.
Save mundry/42daf18c653708d42d5d to your computer and use it in GitHub Desktop.
Java 8 Date/Time-API example
import java.time.Duration;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class Java8DateTimeApiExample {
public static void main(String[] args) {
ZonedDateTime now = ZonedDateTime.now();
int daysOffset = (int) (Math.random() * 10) + 1;
System.out.printf("Subtracting %d day%s\n", daysOffset, daysOffset == 1 ? "" : "s");
ZonedDateTime xDaysAgo = now.minusDays(daysOffset);
// More than 1 week ago?
if (Duration.between(xDaysAgo, now).getSeconds() > Duration.ofDays(7).getSeconds()) {
System.out.println(xDaysAgo.format(DateTimeFormatter.ofPattern("d. M. yyyy")));
} else {
System.out.println(xDaysAgo.format(DateTimeFormatter.ofPattern("d. M. yyyy, HH:mm")));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment