Skip to content

Instantly share code, notes, and snippets.

@sergiandreplace
Created January 13, 2021 08:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sergiandreplace/9ddba78f95c31640db89fd2e3158ee3c to your computer and use it in GitHub Desktop.
Save sergiandreplace/9ddba78f95c31640db89fd2e3158ee3c to your computer and use it in GitHub Desktop.
Tests to play with the Time & Date Java 8 API
import org.junit.Test
import java.time.*
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import java.time.temporal.ChronoField
import java.time.temporal.ChronoUnit
import java.time.temporal.TemporalAdjusters
import java.util.*
import kotlin.time.days
import kotlin.time.minutes
class TimeForRobots {
companion object {
const val MY_BIRTH_INSTANT = "1976-12-18T18:30:22Z"
}
@Test
fun `Clock tick tack`() {
val fixedClock = Clock.fixed(Instant.parse(MY_BIRTH_INSTANT), Clock.systemDefaultZone().zone);
val systemClock = Clock.systemUTC()
val utcClock = Clock.systemUTC()
val defaultZoneClock = Clock.systemDefaultZone()
val spanishClock = Clock.system(ZoneId.of(ZoneId.SHORT_IDS["ECT"]))
val spanishLaterClock = Clock.offset(spanishClock, Duration.ofHours(3))
println("Fixed Clock: ${printClock(fixedClock)}")
println("System clock: ${printClock(systemClock)}")
println("UTC clock: ${printClock(utcClock)}")
println("System default zone clock: ${printClock(defaultZoneClock)}")
println("Spanish clock: ${printClock(spanishClock)}")
println("Spanish later clock: ${printClock(spanishLaterClock)}")
}
private fun printClock(clock: Clock) = "$clock at ${Instant.now(clock)} with ${clock.millis()}"
@Test
fun `Instantiate Instant Instantly`() {
val now = Instant.now()
val birthDateInMs = Instant.ofEpochMilli(219757716000)
val birthDateInSec = Instant.ofEpochSecond(219757716)
val birthParsed = Instant.parse(MY_BIRTH_INSTANT)
println("Now: $now")
println("Birth date in ms: $birthDateInMs")
println("Birth date in seg: $birthDateInSec")
println("Birth date parsed: $birthParsed")
}
@Test
fun `Operating instants`() {
val now = Instant.now()
val tenSecondsLater = now.plusSeconds(10);
val twoDaysLater = now.plus(Period.ofDays(2))
val twoDaysBefore = now.minus(2, ChronoUnit.DAYS)
println("Now: $now")
println("Ten seconds later: $tenSecondsLater")
println("Two days later: $twoDaysLater")
println("Two days before: $twoDaysBefore")
}
}
class LocalTimeTest {
@Test
fun `Time travelling`() {
val now = LocalTime.now()
val inTwoHours = LocalTime.from(now).plusHours(2)
val twoHoursAgo = now.minus(Duration.ofHours(2))
val oneDayLater = now.plus(24, ChronoUnit.HOURS)
val releaseTime = LocalTime.parse("11:00")
val realReleaseTime = releaseTime.plus(Duration.ofSeconds(30))
println("Now: $now")
println("In two hours: $inTwoHours")
println("Two hours ago: $twoHoursAgo")
println("One day later: $oneDayLater")
println("Release time: $releaseTime")
println("Real release time: $realReleaseTime")
}
@Test
fun `Apples and oranges`() {
val now = LocalTime.from(Instant.now())
println("Now: $now")
}
@Test
fun `The proper one`() {
val now = LocalTime.now()
val twoHoursAgo = now.minus(Period.ofDays(2))
println("Now: $now")
println("Two hours ago: $twoHoursAgo")
}
}
class LocalDateTimeTest {
@Test
fun `Time travelling`() {
val now = LocalDateTime.now()
val inTwoDays = LocalDateTime.from(now).plusDays(2)
val twoDaysAgo = now.minus(Duration.ofHours(48))
val oneMonthLater = now.plus(1, ChronoUnit.MONTHS)
val todayAtTen = now.withHour(10).withMinute(0).withSecond(0)
val lastRelease = now.with(TemporalAdjusters.previousOrSame(DayOfWeek.TUESDAY))
val thisYearParty = LocalDateTime.parse("1976-12-18T21:30").withYear(now.year)
val nextParty = if (thisYearParty.isBefore(now)) thisYearParty.plusYears(1) else now
println("Now: $now")
println("In two days: $inTwoDays")
println("Two days ago: $twoDaysAgo")
println("One month later: $oneMonthLater")
println("Today at ten: $todayAtTen")
println("Last Release: $lastRelease")
println("Party this year: $thisYearParty")
println("Next party: $nextParty")
}
@Test
fun `Apples and oranges`() {
val now = LocalDateTime.from(Instant.now())
println("Now: $now")
}
@Test
fun `The proper one`() {
val now = LocalDateTime.now()
val twoDaysAgoTwoHoursAfter = now.minus(Duration.ofHours(48)).plus(Period.ofDays(2))
println("Now: $now")
println("Two days ago two hours after: $twoDaysAgoTwoHoursAfter")
}
}
class LocalDateTest {
@Test
fun `Time travelling`() {
val now = LocalDate.now()
val inTwoDays = LocalDate.from(now).plusDays(2)
val twoDaysAgo = now.minus(Period.ofDays(2))
val oneWeekLater = now.plus(1, ChronoUnit.WEEKS)
val party = LocalDate.parse("2020-12-18")
val hangover = party.plus(Period.ofDays(1))
println("Now: $now")
println("In two days: $inTwoDays")
println("Two days ago: $twoDaysAgo")
println("One week later: $oneWeekLater")
println("Party: $party")
println("Hangover: $hangover")
}
@Test
fun `Apples and oranges`() {
val now = LocalDate.from(Instant.now())
println("Now: $now")
}
@Test
fun `The proper one`() {
val now = LocalDate.now()
val twoDaysAgo = now.minus(Duration.ofHours(48))
println("Now: $now")
println("Two days ago: $twoDaysAgo")
}
}
class ZoneTest {
@Test
fun `Traveling around the world`() {
val zoneIds = ZoneId.getAvailableZoneIds()
val zoneNames = ZoneId.getAvailableZoneIds().joinToString()
println("I have traveled to ${zoneIds.size} places")
println("Have your ever traveled to ...$zoneNames?")
}
@Test
fun `Tokio is so far`() {
val zone = ZoneId.systemDefault()
val now = Instant.now()
val neighbours = ZoneOffset.ofHours(2)
val neighboursTime = Instant.now().atOffset(neighbours)
val tokio = ZoneId.of(ZoneId.SHORT_IDS["JST"])
val tokioNow = now.atZone(tokio)
val tokioTime = tokioNow.toLocalTime()
println("My zone is $zone")
println("Now is $now")
println("Neighbours to $neighbours")
println("Their time is $neighboursTime")
println("Japanese people live in $tokio")
println("Now in Tokio is $tokioNow")
println("Time in Tokio is $tokioTime")
}
}
class AllTogether {
@Test
fun `Time is relative`() {
val spain = ZoneId.of("Europe/Madrid")
val aCompletelyRandomMoment = "2020-10-25T02:30:00"
val initialLocalDateTime = LocalDateTime.parse(aCompletelyRandomMoment)
// Sum 4 hours and convert to ZonedDateTime
val fourHoursAfterLocal = initialLocalDateTime.plus(Duration.ofHours(4))
val fourHoursAfterTimeDate = ZonedDateTime.of(fourHoursAfterLocal, spain)
// Convert to ZonedDateTime and sum 4 hours
val initialTimeDateInSpain = ZonedDateTime.of(initialLocalDateTime, spain)
val fourHoursAfterInSpain = initialTimeDateInSpain.plusHours(4)
println("Initial TimeDate in Spain: ${initialLocalDateTime.hour}")
println("Four hours after local time: ${fourHoursAfterTimeDate.get(ChronoField.HOUR_OF_DAY)}")
println("Four hours after in Spain: ${fourHoursAfterInSpain.get(ChronoField.HOUR_OF_DAY)}")
}
}
class TimeLapses {
@Test
fun `Durable duration`() {
val now = Instant.now()
val duration = Duration.ofHours(2)
val later = now.plus(duration)
println("Now: $now")
println("Duration: $duration")
println("Later: $later")
}
@Test
fun `Periodical period`() {
val now = Instant.now()
val period = Period.ofDays(-2)
val twoDaysAgo = now.plus(period)
println("Now: $now")
println("Period: $period")
println("Two days ago: $twoDaysAgo")
}
@Test
fun `Project duration`() {
val now = LocalDate.now()
val onThePast = LocalDate.of(2020, 1, 17)
val period = Period.between(onThePast, now)
val onTheFuture = now.plus(period)
println("Now: $now")
println("On the past: $onThePast")
println("Period: $period")
println("On the future: $onTheFuture")
}
}
class PrintingTime {
@Test
fun `Print the hour`() {
val time = LocalTime.now()
val formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME
val formattedTime = formatter.format(time)
println("Time: $time")
println("Formatted time: $formattedTime")
}
@Test
fun `Print the hour now!`() {
val time = LocalTime.now()
val formatter = DateTimeFormatter.ISO_LOCAL_TIME
val formattedTime = formatter.format(time)
println("Time: $time")
println("Formatted time: $formattedTime")
}
@Test
fun `Easy format`() {
val date = LocalDate.now()
val formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)
val formattedDate = formatter.format(date)
println("Date: $date")
println("Formatted date: $formattedDate")
}
@Test
fun `I do my own format`() {
val date = LocalDate.now()
val formatter = DateTimeFormatter.ofPattern("dd MMMM yy")
val formattedDate = formatter.format(date)
println("Date: $date")
println("Formatted date: $formattedDate")
}
@Test
fun `Yo habla espanyiolo`() {
val date = LocalDate.now()
val formatter = DateTimeFormatter.ofPattern("dd MMMM yy", Locale.forLanguageTag("es-ES"))
val formattedDate = formatter.format(date)
println("Date: $date")
println("Formatted date: $formattedDate")
}
@Test
fun `En catala si us plau`() {
val date = LocalDate.now()
val formatter = DateTimeFormatter.ofPattern("dd MMMM yy", Locale.forLanguageTag("en"))
val formattedDate = formatter.format(date)
println("Date: $date")
println("Formatted date: $formattedDate")
}
}
class YeOldeDate() {
@Test
fun `Instant from Date`() {
val sourceDate = Date()
val targetInstant = sourceDate.toInstant()
println("Source Date: $sourceDate")
println("Target Instant: $targetInstant")
}
@Test
fun `Instant to Date`() {
val sourceInstant = Instant.now()
val targetDate = Date.from(sourceInstant)
println("Source Instant: $sourceInstant")
println("Target Date: $targetDate")
}
@Test
fun `Date to LocalTime now`() {
val sourceDate = Date()
val targetLocalTime = LocalTime.from(sourceDate.toInstant())
println("Source date: $sourceDate")
println("Target LocalTime: $targetLocalTime")
}
@Test
fun `Date to LocalTime with zone`() {
val sourceDate = Date()
val zone = ZoneId.of("Europe/Madrid")
val targetLocalTime = LocalTime.from(sourceDate.toInstant().atZone(zone))
println("Source date: $sourceDate")
println("Target LocalTime: $targetLocalTime")
}
}
class YeOldeCalendar() {
@Test
fun `Instant from Calendar`() {
val sourceCalendar = GregorianCalendar(Locale.getDefault())
val targetInstant = sourceCalendar.toInstant()
println("Source Calendar: $sourceCalendar")
println("Target Instant: $targetInstant")
}
@Test
fun `Instant to Calendar`() {
val sourceInstant = Instant.now()
val midZonedDateTime = ZonedDateTime.ofInstant(sourceInstant, ZoneId.systemDefault())
val targetCalendar = GregorianCalendar.from(midZonedDateTime)
println("Source Instant: $sourceInstant")
println("Target Calendar: $targetCalendar")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment