How can I convert seconds to time in Scala?

2019-08-08 23:00发布

问题:

println("What is the current number of seconds since midnight?")

val s = readInt

val m = (s/60) % 60

val h = (s/60/60) % 24

That is my current code. I just do not know how to println("") so it displays in hh:mm form. Thank you in advance for any help!

回答1:

I think the answer is

"%02d:%02d".format(h, m)

based on http://www.scala-lang.org/old/node/5153



回答2:

Mostly like @Floris said:

val s = System.currentTimeMillis / 1000
val m = (s/60) % 60
val h = (s/60/60) % 24


val str = "%02d:%02d".format(h, m)
// str = 22:40

Now you could print it, just like you would with regular string.

Since scala 2.10 there is string interpolation feature, which allows you to write things like:

val foo = "bar" 
println(s"I'm $foo!")
// I'm bar!

But I don't think it is much readable (reminds perl):

val str = f"$h%02d:$m%02d"


回答3:

// show elapsed time as hours:mins:seconds
val t1 = System.currentTimeMillis/1000

// ... run some code
val t2 = System.currentTimeMillis/1000
var elapsed_s = (t2 - t1)

// for testing invent some time: 4 hours: 20 minutes: 10 seconds 
elapsed_s=4*60*60 + 20*60 + 10

val residual_s = elapsed_s % 60
val residual_m = (elapsed_s/60) % 60

val elapsed_h = (elapsed_s/60/60)

// display hours as absolute, minutes & seconds as residuals
println("Elapsed time: " + "%02d:%02d:%02d".format(elapsed_h, residual_m, 
residual_s))


标签: scala