├── .gitignore ├── README.md ├── build.gradle.kts ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── library ├── build.gradle.kts └── src │ ├── main │ └── kotlin │ │ └── ca │ │ └── nihk │ │ └── library │ │ ├── RelativeTime.kt │ │ └── TimeRangeFormatter.kt │ └── test │ └── kotlin │ └── ca │ └── nihk │ └── library │ ├── RelativeTimeTest.kt │ └── TestUtils.kt ├── sample ├── build.gradle.kts └── src │ └── main │ └── kotlin │ └── ca │ └── nihk │ └── sample │ └── main.kt └── settings.gradle.kts /.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | .idea 3 | .gradle 4 | build/ 5 | local.properties -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # RelativeTime 2 | A library that lets you define the language of relative time, e.g. "5 hours ago" or "1 month from now" and so on. 3 | 4 | ## How to use: 5 | Start with the DSL builder like so: 6 | 7 | ``` 8 | val relativeTime = relativeTime { 9 | // ... 10 | } 11 | ``` 12 | 13 | Add any number of `timeRangeFormatter` builders in that block to set the kinds of output you want to use within an interval of time: 14 | 15 | ``` 16 | // From now til 1 hour from now, this will print in a 'minutes from now' style. 17 | timeRangeFormatter(now exclusiveToInclusive 1.toDuration(DurationUnit.HOURS)) { info -> 18 | "${info.delta.inWholeMinutes} minutes from now" 19 | } 20 | ``` 21 | 22 | There's also other builder functions like `timeZone` and `currentTimeProvider`. 23 | 24 | Once that's done, any values passed to its `RelativeTime.from` function that fall within the range(s) of the `TimeRangeFormatter`(s) that it owns will output the language you've defined: 25 | 26 | ``` 27 | val currentTime = System.currentTimeMillis().toDuration(DurationUnit.MILLISECONDS) 28 | val fiveMinutes = 5.toDuration(DurationUnit.MILLISECONDS) 29 | relativeTime.from(currentTime + fiveMinutes).let(::println) // prints "5 minutes from now" 30 | ``` 31 | 32 | For more examples, see the sample gradle module in this project or the TestUtils.kt file in `library/src/test`. 33 | 34 | ## Install: 35 | 36 | Copy and paste! It's only two small files. This was originally published to JCenter, but that's gonezo. 37 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile 2 | 3 | buildscript { 4 | repositories { 5 | mavenCentral() 6 | } 7 | dependencies { 8 | classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.0") 9 | } 10 | } 11 | 12 | allprojects { 13 | repositories { 14 | mavenCentral() 15 | } 16 | 17 | tasks.withType().configureEach { 18 | kotlinOptions { 19 | jvmTarget = JavaVersion.VERSION_1_8.toString() 20 | freeCompilerArgs = listOf( 21 | "-Xuse-experimental=kotlin.time.ExperimentalTime" 22 | ) 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | kotlin.code.style=official -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nihk/RelativeTime/89ba5837a1b0b6d21b66c0ebf30e6929f717e4cf/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS='"-Xmx64m"' 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS="-Xmx64m" 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /library/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | kotlin("jvm") 3 | } 4 | 5 | repositories { 6 | mavenCentral() 7 | } 8 | 9 | dependencies { 10 | implementation(kotlin("stdlib")) 11 | testImplementation("junit:junit:4.13.2") 12 | } 13 | -------------------------------------------------------------------------------- /library/src/main/kotlin/ca/nihk/library/RelativeTime.kt: -------------------------------------------------------------------------------- 1 | package ca.nihk.library 2 | 3 | import java.util.TimeZone 4 | import kotlin.time.Duration 5 | import kotlin.time.DurationUnit 6 | import kotlin.time.toDuration 7 | 8 | fun relativeTime(block: RelativeTime.Builder.() -> Unit): RelativeTime { 9 | return RelativeTime.Builder() 10 | .apply(block) 11 | .build() 12 | } 13 | 14 | class RelativeTime( 15 | private val timeRangeFormatters: List>, 16 | private val timeZone: TimeZone = TimeZone.getDefault(), 17 | private val currentTimeProvider: () -> Duration, 18 | private val fallback: T? = null, 19 | strictMode: Boolean = true 20 | ) { 21 | init { 22 | if (strictMode) { 23 | checkForOverlappingTimeRanges() 24 | } 25 | } 26 | 27 | fun from(timeInMillis: String?): T? { 28 | val parsed = timeInMillis?.toLongOrNull() ?: return fallback 29 | return from(parsed) 30 | } 31 | 32 | fun from(timeInMillis: Long): T { 33 | return from(timeInMillis.toDuration(DurationUnit.MILLISECONDS)) 34 | } 35 | 36 | fun from(time: Duration): T { 37 | val delta = time - currentTimeProvider() 38 | 39 | return timeRangeFormatters.find { delta in it } 40 | ?.format?.invoke(TimeRangeFormatter.Info(delta, time, timeZone)) 41 | ?: fallback 42 | ?: error("Unhandled time: $time") 43 | } 44 | 45 | private fun checkForOverlappingTimeRanges() { 46 | val ranges = timeRangeFormatters 47 | for (i in ranges.indices) { 48 | for (j in i + 1 until ranges.size) { 49 | val left = ranges[i] 50 | val right = ranges[j] 51 | check(!left.overlapsWith(right)) { "$left has an overlapping range with $right" } 52 | } 53 | } 54 | } 55 | 56 | class Builder { 57 | private val timeRangeFormatters = mutableListOf>() 58 | private var timeZone: TimeZone? = null 59 | private var currentTimeProvider: (() -> Duration)? = null 60 | private var fallback: T? = null 61 | private var strictMode: Boolean = true 62 | 63 | fun timeRangeFormatter( 64 | range: ClosedRange, 65 | format: (info: TimeRangeFormatter.Info) -> T 66 | ) = apply { 67 | timeRangeFormatter(TimeRangeFormatter(range, format)) 68 | } 69 | 70 | fun timeRangeFormatter(timeRangeFormatter: TimeRangeFormatter) = apply { 71 | timeRangeFormatters += timeRangeFormatter 72 | } 73 | 74 | fun timeZone(timeZone: TimeZone) = apply { 75 | this.timeZone = timeZone 76 | } 77 | 78 | fun currentTimeProvider(currentTimeProvider: () -> Duration) = apply { 79 | this.currentTimeProvider = currentTimeProvider 80 | } 81 | 82 | fun fallback(fallback: T) = apply { 83 | this.fallback = fallback 84 | } 85 | 86 | fun strictMode(strictMode: Boolean) = apply { 87 | this.strictMode = strictMode 88 | } 89 | 90 | fun build(): RelativeTime { 91 | return RelativeTime( 92 | timeRangeFormatters = timeRangeFormatters, 93 | timeZone = timeZone ?: TimeZone.getDefault(), 94 | currentTimeProvider = currentTimeProvider ?: { System.currentTimeMillis().toDuration(DurationUnit.MILLISECONDS) }, 95 | fallback = fallback, 96 | strictMode = strictMode 97 | ) 98 | } 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /library/src/main/kotlin/ca/nihk/library/TimeRangeFormatter.kt: -------------------------------------------------------------------------------- 1 | package ca.nihk.library 2 | 3 | import java.util.TimeZone 4 | import kotlin.time.Duration 5 | import kotlin.time.DurationUnit 6 | import kotlin.time.toDuration 7 | 8 | class TimeRangeFormatter( 9 | private val range: ClosedRange, 10 | internal val format: (info: Info) -> T 11 | ) { 12 | internal operator fun contains(duration: Duration): Boolean { 13 | return duration in range 14 | } 15 | 16 | internal fun overlapsWith(other: TimeRangeFormatter): Boolean { 17 | return range.start in other.range || range.endInclusive in other.range 18 | } 19 | 20 | data class Info( 21 | val delta: Duration, 22 | val currentTime: Duration, 23 | val timeZone: TimeZone 24 | ) 25 | } 26 | 27 | val now = Duration.ZERO 28 | val dawnOfTime = Long.MIN_VALUE.toDuration(DurationUnit.MILLISECONDS) 29 | val endOfTime = Long.MAX_VALUE.toDuration(DurationUnit.MILLISECONDS) 30 | 31 | infix fun Duration.inclusiveToInclusive(end: Duration): ClosedRange { 32 | return this..end 33 | } 34 | 35 | infix fun Duration.inclusiveToExclusive(end: Duration): ClosedRange { 36 | return this..(end - 1.toDuration(DurationUnit.MILLISECONDS)) 37 | } 38 | 39 | infix fun Duration.exclusiveToInclusive(end: Duration): ClosedRange { 40 | return (this + 1.toDuration(DurationUnit.MILLISECONDS))..end 41 | } 42 | 43 | infix fun Duration.exclusiveToExclusive(end: Duration): ClosedRange { 44 | return (this + 1.toDuration(DurationUnit.MILLISECONDS))..(end - 1.toDuration(DurationUnit.MILLISECONDS)) 45 | } 46 | -------------------------------------------------------------------------------- /library/src/test/kotlin/ca/nihk/library/RelativeTimeTest.kt: -------------------------------------------------------------------------------- 1 | package ca.nihk.library 2 | 3 | import org.junit.Assert 4 | import org.junit.Assert.fail 5 | import org.junit.Test 6 | import java.util.TimeZone 7 | import kotlin.time.DurationUnit 8 | import kotlin.time.toDuration 9 | 10 | class RelativeTimeTest { 11 | private val toronto: TimeZone = TimeZone.getTimeZone("America/Toronto") 12 | 13 | @Test 14 | fun `just over two years ago`() { 15 | validateRelativeTime( 16 | timeZone = toronto, 17 | timeRangeFormatters = TestUtils.timeRangeFormatters, 18 | expected = "January 1, 2017", 19 | now = 1547528400000L, // Tuesday, January 15, 2019 12:00:00 AM GMT-05:00 20 | date = 1483246800000L // Sunday, January 1, 2017 12:00:00 AM GMT-05:00 21 | ) 22 | } 23 | 24 | @Test 25 | fun `around six months ago`() { 26 | validateRelativeTime( 27 | timeZone = toronto, 28 | timeRangeFormatters = TestUtils.timeRangeFormatters, 29 | expected = "June 15", 30 | now = 1547528400000L, // Tuesday, January 15, 2019 12:00:00 AM GMT-05:00 31 | date = 1529035200000L // Friday, June 15, 2018 12:00:00 AM GMT-04:00 32 | ) 33 | } 34 | 35 | @Test 36 | fun `twelve hours ago`() { 37 | validateRelativeTime( 38 | timeZone = toronto, 39 | timeRangeFormatters = TestUtils.timeRangeFormatters, 40 | expected = "January 14", 41 | now = 1547528400000L, // Tuesday, January 15, 2019 12:00:00 AM GMT-05:00 42 | date = 1547485200000L // Monday, January 14, 2019 12:00:00 PM GMT-05:00 43 | ) 44 | } 45 | 46 | @Test 47 | fun `eleven hours, fifty-nine minutes, and fifty-nine seconds ago`() { 48 | validateRelativeTime( 49 | timeZone = toronto, 50 | timeRangeFormatters = TestUtils.timeRangeFormatters, 51 | expected = "11 hours ago", 52 | now = 1547528400000L, // Tuesday, January 15, 2019 12:00:00 AM GMT-05:00 53 | date = 1547485201000L // Monday, January 14, 2019 12:00:01 PM GMT-05:00 54 | ) 55 | } 56 | 57 | @Test 58 | fun `three hours ago`() { 59 | validateRelativeTime( 60 | timeZone = toronto, 61 | timeRangeFormatters = TestUtils.timeRangeFormatters, 62 | expected = "3 hours ago", 63 | now = 1547528400000L, // Tuesday, January 15, 2019 12:00:00 AM GMT-05:00 64 | date = 1547517600000L // Monday, January 14, 2019 9:00:00 PM GMT-05:00 65 | ) 66 | } 67 | 68 | @Test 69 | fun `one hour ago`() { 70 | validateRelativeTime( 71 | timeZone = toronto, 72 | timeRangeFormatters = TestUtils.timeRangeFormatters, 73 | expected = "An hour ago", 74 | now = 1547528400000L, // Tuesday, January 15, 2019 12:00:00 AM GMT-05:00 75 | date = 1547524800000L // Monday, January 14, 2019 11:00:00 PM GMT-05:00 76 | ) 77 | } 78 | 79 | @Test 80 | fun `thirty three minutes ago`() { 81 | validateRelativeTime( 82 | timeZone = toronto, 83 | timeRangeFormatters = TestUtils.timeRangeFormatters, 84 | expected = "33 minutes ago", 85 | now = 1547528400000L, // Tuesday, January 15, 2019 12:00:00 AM GMT-05:00 86 | date = 1547526420000L // Monday, January 14, 2019 11:27:00 PM GMT-05:00 87 | ) 88 | } 89 | 90 | @Test 91 | fun `one minute, thirty seconds ago`() { 92 | validateRelativeTime( 93 | timeZone = toronto, 94 | timeRangeFormatters = TestUtils.timeRangeFormatters, 95 | expected = "A minute ago", 96 | now = 1547528400000L, // Tuesday, January 15, 2019 12:00:00 AM GMT-05:00 97 | date = 1547528310000L // Monday, January 14, 2019 11:58:30 PM GMT-05:00 98 | ) 99 | } 100 | 101 | @Test 102 | fun `thirty seconds ago`() { 103 | validateRelativeTime( 104 | timeZone = toronto, 105 | timeRangeFormatters = TestUtils.timeRangeFormatters, 106 | expected = "Seconds ago", 107 | now = 1547528400000L, // Tuesday, January 15, 2019 12:00:00 AM GMT-05:00 108 | date = 1547528370000L // Monday, January 14, 2019 11:59:30 PM GMT-05:00 109 | ) 110 | } 111 | 112 | @Test 113 | fun `same time as now`() { 114 | validateRelativeTime( 115 | timeZone = toronto, 116 | timeRangeFormatters = TestUtils.timeRangeFormatters, 117 | expected = "Now", 118 | now = 1547528400000L, // Tuesday, January 15, 2019 12:00:00 AM GMT-05:00 119 | date = 1547528400000L // Tuesday, January 15, 2019 12:00:00 AM GMT-05:00 120 | ) 121 | } 122 | 123 | @Test 124 | fun `five seconds from now`() { 125 | validateRelativeTime( 126 | timeZone = toronto, 127 | timeRangeFormatters = TestUtils.timeRangeFormatters, 128 | expected = "Seconds from now", 129 | now = 1547528400000L, // Tuesday, January 15, 2019 12:00:00 AM GMT-05:00 130 | date = 1547528405000L // Tuesday, January 15, 2019 12:00:05 AM GMT-05:00 131 | ) 132 | } 133 | 134 | @Test 135 | fun `one minute, five seconds from now`() { 136 | validateRelativeTime( 137 | timeZone = toronto, 138 | timeRangeFormatters = TestUtils.timeRangeFormatters, 139 | expected = "In one minute", 140 | now = 1547528400000L, // Tuesday, January 15, 2019 12:00:00 AM GMT-05:00 141 | date = 1547528465000L // Tuesday, January 15, 2019 12:01:05 AM GMT-05:00 142 | ) 143 | } 144 | 145 | @Test 146 | fun `a half hour from now`() { 147 | validateRelativeTime( 148 | timeZone = toronto, 149 | timeRangeFormatters = TestUtils.timeRangeFormatters, 150 | expected = "In 30 minutes", 151 | now = 1547528400000L, // Tuesday, January 15, 2019 12:00:00 AM GMT-05:00 152 | date = 1547530200000L // Tuesday, January 15, 2019 12:30:00 AM GMT-05:00 153 | ) 154 | } 155 | 156 | @Test 157 | fun `ninety minutes from now`() { 158 | validateRelativeTime( 159 | timeZone = toronto, 160 | timeRangeFormatters = TestUtils.timeRangeFormatters, 161 | expected = "In one hour", 162 | now = 1547528400000L, // Tuesday, January 15, 2019 12:00:00 AM GMT-05:00 163 | date = 1547533800000L // Tuesday, January 15, 2019 1:30:00 AM GMT-05:00 164 | ) 165 | } 166 | 167 | @Test 168 | fun `seven hours from now`() { 169 | validateRelativeTime( 170 | timeZone = toronto, 171 | timeRangeFormatters = TestUtils.timeRangeFormatters, 172 | expected = "In 7 hours", 173 | now = 1547528400000L, // Tuesday, January 15, 2019 12:00:00 AM GMT-05:00 174 | date = 1547553600000L // Tuesday, January 15, 2019 7:00:00 AM GMT-05:00 175 | ) 176 | } 177 | 178 | @Test 179 | fun `seven months from now`() { 180 | validateRelativeTime( 181 | timeZone = toronto, 182 | timeRangeFormatters = TestUtils.timeRangeFormatters, 183 | expected = "August 15", 184 | now = 1547528400000L, // Tuesday, January 15, 2019 12:00:00 AM GMT-05:00 185 | date = 1565841600000L // Thursday, August 15, 2019 12:00:00 AM GMT-04:00 186 | ) 187 | } 188 | 189 | @Test 190 | fun `two years from now`() { 191 | validateRelativeTime( 192 | timeZone = toronto, 193 | timeRangeFormatters = TestUtils.timeRangeFormatters, 194 | expected = "January 15, 2021", 195 | now = 1547528400000L, // Tuesday, January 15, 2019 12:00:00 AM GMT-05:00 196 | date = 1610686800000L // Friday, January 15, 2021 12:00:00 AM GMT-05:00 197 | ) 198 | } 199 | 200 | @Test 201 | fun `toronto timezone looking at tokyo`() { 202 | validateRelativeTime( 203 | timeZone = toronto, 204 | timeRangeFormatters = TestUtils.timeRangeFormatters, 205 | expected = "August 13", 206 | now = 1597150800000L, // Tuesday, August 11, 2020 9:00:00 AM GMT-04:00 207 | date = 1597294800000L // Thursday August 13, 2020 14:00:00 PM GMT+09:00 208 | ) 209 | } 210 | 211 | @Test 212 | fun `vancouver timezone looking at tokyo`() { 213 | validateRelativeTime( 214 | timeZone = TimeZone.getTimeZone("America/Vancouver"), 215 | timeRangeFormatters = TestUtils.timeRangeFormatters, 216 | expected = "August 12", 217 | now = 1597150800000L, // Tuesday, August 11, 2020 6:00:00 AM GMT-07:00 218 | date = 1597294800000L // Thursday August 13, 2020 14:00:00 PM GMT+09:00 219 | ) 220 | } 221 | 222 | @Test 223 | fun `from string, five hours ago`() { 224 | validateRelativeTime( 225 | timeZone = toronto, 226 | timeRangeFormatters = TestUtils.timeRangeFormatters, 227 | expected = "5 hours ago", 228 | now = 1547528400000L, // Tuesday, January 15, 2019 12:00:00 AM GMT-05:00 229 | date = "1547510400000" // Monday, January 14, 2019 7:00:00 PM GMT-05:00 230 | ) 231 | } 232 | 233 | @Test 234 | fun `invalid string returns fallback`() { 235 | validateRelativeTime( 236 | timeZone = toronto, 237 | timeRangeFormatters = TestUtils.timeRangeFormatters, 238 | expected = "fallback", 239 | fallback = "fallback", 240 | now = 1547528400000L, // Tuesday, January 15, 2019 12:00:00 AM GMT-05:00 241 | date = "this is an invalid date" 242 | ) 243 | } 244 | 245 | @Test 246 | fun `empty string returns fallback`() { 247 | validateRelativeTime( 248 | timeZone = toronto, 249 | timeRangeFormatters = TestUtils.timeRangeFormatters, 250 | expected = "fallback", 251 | fallback = "fallback", 252 | now = 1547528400000L, // Tuesday, January 15, 2019 12:00:00 AM GMT-05:00 253 | date = "" 254 | ) 255 | } 256 | 257 | @Test 258 | fun `null string returns fallback`() { 259 | validateRelativeTime( 260 | timeZone = toronto, 261 | timeRangeFormatters = TestUtils.timeRangeFormatters, 262 | expected = "fallback", 263 | fallback = "fallback", 264 | now = 1547528400000L, // Tuesday, January 15, 2019 12:00:00 AM GMT-05:00 265 | date = null 266 | ) 267 | } 268 | 269 | @Test 270 | fun `epoch start input`() { 271 | validateRelativeTime( 272 | timeZone = toronto, 273 | timeRangeFormatters = TestUtils.timeRangeFormatters, 274 | expected = "December 31, 1969", 275 | now = 1547528400000L, // Tuesday, January 15, 2019 12:00:00 AM GMT-05:00 276 | date = 0L // Wednesday, December 31, 1969 7:00:00 PM GMT-05:00 277 | ) 278 | } 279 | 280 | @Test(expected = IllegalStateException::class) 281 | fun `overlapping time ranges throw when checking for overlaps is true`() { 282 | createRelativeTime( 283 | nowMillis = 0L, 284 | timeZone = toronto, 285 | timeRangeFormatters = TestUtils.overlapping, 286 | fallback = "fallback", 287 | strictMode = true 288 | ) 289 | 290 | fail() 291 | } 292 | 293 | @Test 294 | fun `overlapping time ranges don't throw when checking for overlaps is false`() { 295 | createRelativeTime( 296 | nowMillis = 0L, 297 | timeZone = toronto, 298 | timeRangeFormatters = TestUtils.overlapping, 299 | fallback = "fallback", 300 | strictMode = false 301 | ) 302 | } 303 | 304 | private fun validateRelativeTime( 305 | expected: String?, 306 | date: Long, 307 | now: Long, 308 | timeZone: TimeZone, 309 | timeRangeFormatters: List>, 310 | fallback: String = "", 311 | strictMode: Boolean = true 312 | ) { 313 | val relativeTime = createRelativeTime(now, timeZone, timeRangeFormatters, fallback, strictMode) 314 | 315 | val result = relativeTime.from(date) 316 | 317 | Assert.assertEquals(expected, result) 318 | } 319 | 320 | private fun validateRelativeTime( 321 | expected: String?, 322 | date: String?, 323 | now: Long, 324 | timeZone: TimeZone, 325 | timeRangeFormatters: List>, 326 | fallback: String = "", 327 | checkForOverlappingTimeRanges: Boolean = true 328 | ) { 329 | val relativeTime = createRelativeTime(now, timeZone, timeRangeFormatters, fallback, checkForOverlappingTimeRanges) 330 | 331 | val result = relativeTime.from(date) 332 | 333 | Assert.assertEquals(expected, result) 334 | } 335 | 336 | private fun createRelativeTime( 337 | nowMillis: Long, 338 | timeZone: TimeZone, 339 | timeRangeFormatters: List>, 340 | fallback: T, 341 | strictMode: Boolean 342 | ): RelativeTime { 343 | return relativeTime { 344 | timeRangeFormatters.forEach(::timeRangeFormatter) 345 | timeZone(timeZone) 346 | fallback(fallback) 347 | strictMode(strictMode) 348 | currentTimeProvider { nowMillis.toDuration(DurationUnit.MILLISECONDS) } 349 | } 350 | } 351 | } 352 | -------------------------------------------------------------------------------- /library/src/test/kotlin/ca/nihk/library/TestUtils.kt: -------------------------------------------------------------------------------- 1 | package ca.nihk.library 2 | 3 | import java.text.SimpleDateFormat 4 | import java.util.Date 5 | import java.util.Locale 6 | import java.util.TimeZone 7 | import kotlin.math.absoluteValue 8 | import kotlin.time.Duration 9 | import kotlin.time.DurationUnit 10 | import kotlin.time.toDuration 11 | 12 | internal object TestUtils { 13 | private fun toDateString(datePattern: String, time: Duration, timeZone: TimeZone): String { 14 | // Keep a consistent style of Locale, regardless of device Locale 15 | val locale = Locale.US 16 | 17 | return SimpleDateFormat(datePattern, locale) 18 | .apply { this.timeZone = timeZone } 19 | .format(Date(time.inWholeMilliseconds)) 20 | } 21 | 22 | internal val timeRangeFormatters = listOf( 23 | TimeRangeFormatter(dawnOfTime inclusiveToInclusive (-365).toDuration(DurationUnit.DAYS)) { info -> 24 | toDateString("MMMM d, yyyy", info.currentTime, info.timeZone) 25 | }, 26 | TimeRangeFormatter((-365).toDuration(DurationUnit.DAYS) exclusiveToInclusive (-12).toDuration(DurationUnit.HOURS)) { info -> 27 | toDateString("MMMM d", info.currentTime, info.timeZone) 28 | }, 29 | TimeRangeFormatter((-12).toDuration(DurationUnit.HOURS) exclusiveToInclusive (-2).toDuration(DurationUnit.HOURS)) { info -> 30 | "${info.delta.inWholeHours.absoluteValue.toInt()} hours ago" 31 | }, 32 | TimeRangeFormatter((-2).toDuration(DurationUnit.HOURS) exclusiveToInclusive (-1).toDuration(DurationUnit.HOURS)) { 33 | "An hour ago" 34 | }, 35 | TimeRangeFormatter((-1).toDuration(DurationUnit.HOURS) exclusiveToInclusive (-2).toDuration(DurationUnit.MINUTES)) { info -> 36 | "${info.delta.inWholeMinutes.absoluteValue.toInt()} minutes ago" 37 | }, 38 | TimeRangeFormatter((-2).toDuration(DurationUnit.MINUTES) exclusiveToInclusive (-1).toDuration(DurationUnit.MINUTES)) { 39 | "A minute ago" 40 | }, 41 | TimeRangeFormatter((-1).toDuration(DurationUnit.MINUTES) exclusiveToExclusive now) { 42 | "Seconds ago" 43 | }, 44 | TimeRangeFormatter(now inclusiveToInclusive now) { 45 | "Now" 46 | }, 47 | TimeRangeFormatter(now exclusiveToExclusive 1.toDuration(DurationUnit.MINUTES)) { 48 | "Seconds from now" 49 | }, 50 | TimeRangeFormatter(1.toDuration(DurationUnit.MINUTES) inclusiveToExclusive 2.toDuration(DurationUnit.MINUTES)) { 51 | "In one minute" 52 | }, 53 | TimeRangeFormatter(2.toDuration(DurationUnit.MINUTES) inclusiveToExclusive 1.toDuration(DurationUnit.HOURS)) { info -> 54 | "In ${info.delta.inWholeMinutes.toInt()} minutes" 55 | }, 56 | TimeRangeFormatter(1.toDuration(DurationUnit.HOURS) inclusiveToExclusive 2.toDuration(DurationUnit.HOURS)) { 57 | "In one hour" 58 | }, 59 | TimeRangeFormatter(2.toDuration(DurationUnit.HOURS) inclusiveToExclusive 12.toDuration(DurationUnit.HOURS)) { info -> 60 | "In ${info.delta.inWholeHours.toInt()} hours" 61 | }, 62 | TimeRangeFormatter(12.toDuration(DurationUnit.HOURS) inclusiveToExclusive 365.toDuration(DurationUnit.DAYS)) { info -> 63 | toDateString("MMMM d", info.currentTime, info.timeZone) 64 | }, 65 | TimeRangeFormatter(365.toDuration(DurationUnit.DAYS) inclusiveToInclusive endOfTime) { info -> 66 | toDateString("MMMM d, yyyy", info.currentTime, info.timeZone) 67 | } 68 | ) 69 | 70 | internal val overlapping = listOf( 71 | TimeRangeFormatter(1.toDuration(DurationUnit.MINUTES) inclusiveToExclusive 2.toDuration(DurationUnit.MINUTES)) { 72 | "" 73 | }, 74 | TimeRangeFormatter(1.toDuration(DurationUnit.MINUTES) inclusiveToExclusive 1.toDuration(DurationUnit.HOURS)) { 75 | "" 76 | } 77 | ) 78 | } 79 | -------------------------------------------------------------------------------- /sample/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | kotlin("jvm") 3 | } 4 | 5 | repositories { 6 | mavenCentral() 7 | } 8 | 9 | dependencies { 10 | implementation(kotlin("stdlib")) 11 | implementation(project(":library")) 12 | testImplementation("junit:junit:4.13.2") 13 | } 14 | -------------------------------------------------------------------------------- /sample/src/main/kotlin/ca/nihk/sample/main.kt: -------------------------------------------------------------------------------- 1 | package ca.nihk.sample 2 | 3 | import ca.nihk.library.* 4 | import kotlin.math.absoluteValue 5 | import kotlin.time.DurationUnit 6 | import kotlin.time.toDuration 7 | 8 | fun main() { 9 | val currentTimeProvider = { System.currentTimeMillis().toDuration(DurationUnit.MILLISECONDS) } 10 | 11 | val relativeTime = relativeTime { 12 | currentTimeProvider(currentTimeProvider) 13 | 14 | timeRangeFormatter((-1).toDuration(DurationUnit.HOURS) exclusiveToExclusive now) { info -> 15 | "${info.delta.inWholeMinutes.absoluteValue} minutes ago" 16 | } 17 | timeRangeFormatter(now inclusiveToInclusive now) { info -> 18 | "Now! And you're in ${info.timeZone.displayName}" 19 | } 20 | timeRangeFormatter(now exclusiveToInclusive 1.toDuration(DurationUnit.HOURS)) { info -> 21 | "Epoch: ${(info.currentTime + info.delta).inWholeMilliseconds}" 22 | } 23 | } 24 | 25 | relativeTime.from(currentTimeProvider() - 5.toDuration(DurationUnit.MINUTES)).let(::println) // 5 minutes ago 26 | relativeTime.from(currentTimeProvider()).let(::println) // Now! And you're in Eastern Standard Time 27 | relativeTime.from(currentTimeProvider() + 5.toDuration(DurationUnit.MINUTES)).let(::println) // Epoch: 1637882818518 28 | } 29 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | include( 2 | ":library", 3 | ":sample" 4 | ) 5 | rootProject.name = "RelativeTime" --------------------------------------------------------------------------------