Last active
August 29, 2015 14:02
-
-
Save mundry/42daf18c653708d42d5d to your computer and use it in GitHub Desktop.
Java 8 Date/Time-API example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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