Created
January 13, 2017 15:54
-
-
Save unserializable/38ac812a9988b4361eb2b245e84c9c83 to your computer and use it in GitHub Desktop.
Temporal play, with Friday the 13th 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.math.BigDecimal; | |
import java.math.RoundingMode; | |
import java.time.*; | |
import java.time.format.DateTimeFormatter; | |
import java.time.temporal.ChronoUnit; | |
import java.time.temporal.TemporalQuery; | |
import static java.time.DayOfWeek.FRIDAY; | |
import static java.time.temporal.ChronoField.DAY_OF_MONTH; | |
/** | |
* <p> | |
* For the next Friday the 13th: | |
* </p> | |
* <ul> | |
* <li>{@link DateTimeFormatter}</li> | |
* <li>{@link TemporalQuery}</li> | |
* <li>{@link LocalDateTime}</li> | |
* <li>{@link ZoneId}</li> | |
* <li>{@link OffsetDateTime}</li> | |
* <li>{@link ZoneOffset}</li> | |
* <li>{@link Duration}</li> | |
* </ul> | |
* <p> | |
* Initial output on 13th of January, 2017: | |
* | |
<pre>Lucky bastard, today is already Friday 13th of January (2017). | |
Next upcoming lucky day is Friday 13th of October (2017). | |
For that the wait is approximately 272.25937500000003 days.</pre> | |
* </p> | |
* | |
* @author Taimo Peelo | |
*/ | |
public class NextFriday13th { | |
private static final DateTimeFormatter FORMATTER = | |
DateTimeFormatter.ofPattern("eeee dd'th' 'of' MMMM (yyyy)"); | |
private static final TemporalQuery<Boolean> isFridayThe13th = | |
t -> (13 == t.get(DAY_OF_MONTH)) && (FRIDAY == DayOfWeek.from(t)); | |
public static void main(String[] args) { | |
// | |
// Maybe its already here? | |
// | |
LocalDateTime now = LocalDateTime.now(); | |
if (now.query(isFridayThe13th)) { | |
System.out.println("Lucky bastard, today is already " + FORMATTER.format(now) + "."); | |
} | |
// | |
// When will it be next, then? | |
// | |
ZoneId systemZO = ZoneOffset.systemDefault(); | |
OffsetDateTime offsetNow = now.atOffset(systemZO.getRules().getOffset(now)); | |
OffsetDateTime upcoming = offsetNow.truncatedTo(ChronoUnit.DAYS).plus(1, ChronoUnit.DAYS); | |
while (!upcoming.query(isFridayThe13th)) | |
upcoming = upcoming.plus(1, ChronoUnit.HALF_DAYS); | |
System.out.println("Next upcoming lucky day is " + FORMATTER.format(upcoming) + "."); | |
// | |
// But how long until the lucky day? | |
// | |
Duration waitingTime = Duration.between(offsetNow, upcoming); | |
BigDecimal approxDaysToWait = | |
new BigDecimal(waitingTime.get(ChronoUnit.SECONDS)) | |
.divide(BigDecimal.valueOf(3600*24), 2, RoundingMode.HALF_UP) ; | |
System.out.println("For that the wait is approximately " + approxDaysToWait + " days."); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment