Last active
August 29, 2015 14:01
-
-
Save chrissie1/e16c794abd503117dd3a to your computer and use it in GitHub Desktop.
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
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) | |
}) | |
}) | |
} | |
} | |
} | |
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
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