Created
May 3, 2017 02:05
-
-
Save krishnanraman/0a17ef012c1cb28edf3e44214f5d4e83 to your computer and use it in GitHub Desktop.
human readable time difference java scala
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
scala> import java.util.concurrent.TimeUnit | |
import java.util.concurrent.TimeUnit | |
scala> val units = List((TimeUnit.DAYS,"days"),(TimeUnit.HOURS,"hours"), (TimeUnit.MINUTES,"minutes"), (TimeUnit.SECONDS,"seconds")) | |
units: List[(java.util.concurrent.TimeUnit, String)] = List((DAYS,days), (HOURS,hours), (MINUTES,minutes), (SECONDS,seconds)) | |
scala> def humanReadable(timediff:Long):String = { | |
| val init = ("", timediff) | |
| units.foldLeft(init){ case (acc,next) => | |
| val (human, rest) = acc | |
| val (unit, name) = next | |
| val res = unit.convert(rest,TimeUnit.MILLISECONDS) | |
| val str = if (res > 0) human + " " + res + " " + name else human | |
| val diff = rest - TimeUnit.MILLISECONDS.convert(res,unit) | |
| (str,diff) | |
| }._1 | |
| } | |
humanReadable: (timediff: Long)String | |
scala> humanReadable((2 *24*60*60+ 5 *60*60+ 7 *60+ 9 )*1000) | |
res0: String = " 2 days 5 hours 7 minutes 9 seconds" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've written something similar in a slightly (IMO) more functional way to work with a Scala
Duration
usingfoldLeft
and without theTimeUnit->String
tuple: