Skip to content

Instantly share code, notes, and snippets.

@chrissie1
Last active August 29, 2015 14:01
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 chrissie1/e16c794abd503117dd3a to your computer and use it in GitHub Desktop.
Save chrissie1/e16c794abd503117dd3a to your computer and use it in GitHub Desktop.
package org.humanizer.jvm.tests
import org.spek.Spek
import org.spek.givenData
import org.humanizer.jvm.humanize
import org.spek.shouldEqual
import org.humanizer.jvm.dehumanize
import org.humanizer.jvm.milliSecondsToTimespan
public class TimeSpanTests(): Spek() {
{
var data = listOf(
1 to "0 seconds",
1000 to "1 second",
5000 to "5 seconds",
60000 to "1 minute",
61000 to "1 minute and 1 second",
65000 to "1 minute and 5 seconds",
120000 to "2 minutes",
121000 to "2 minutes and 1 second",
125000 to "2 minutes and 5 seconds")
givenData(data) {
val (input, expected) = it
on("calling toTimespan on $input", {
val actual = input.milliSecondsToTimespan()
it("should become ${it.component2()}", {
shouldEqual(expected, actual)
})
})
}
}
}
package org.humanizer.jvm
fun Int.milliSecondsToTimespan(milliSecondPrecision : Boolean = true) : String
{
return this.toLong().milliSecondsToTimespan()
}
// Honestly stolen from here http://stackoverflow.com/a/2795991
fun Long.milliSecondsToTimespan() : String{
val sb = StringBuffer()
val diffInSeconds = this / 1000
val seconds = if(diffInSeconds >= 60) diffInSeconds % 60 else diffInSeconds
val minutes = if((diffInSeconds / 60) >= 60) diffInSeconds % (60* 60) else diffInSeconds / 60
val hours = if((diffInSeconds / 3600) >= 24) diffInSeconds % (60*60*24) else diffInSeconds / 3600
val days = diffInSeconds / 60 / 60 / 24
if (days > 0) {
sb.append("day".toQuantity(days));
if (hours > 0) {
sb.append(" and ${"hour".toQuantity(hours)}");
}
} else if (hours > 0) {
sb.append("hour".toQuantity(hours))
if (minutes > 0) {
sb.append(" and ${"minute".toQuantity(minutes)}");
}
} else if (minutes > 0) {
sb.append("minute".toQuantity(minutes))
if (seconds > 0) {
sb.append(" and ${"second".toQuantity(seconds)}");
}
} else
{
sb.append("second".toQuantity(seconds));
}
return sb.toString()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment