我怎么能转换秒的时间在Scala呢?(How can I convert seconds to ti

2019-10-18 17:01发布

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

val s = readInt

val m = (s/60) % 60

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

这是我当前的代码。 我只是不知道如何给println(“”),所以它显示在HH:MM形式。 预先感谢您的任何帮助!

Answer 1:

我认为答案是

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

基于http://www.scala-lang.org/old/node/5153



Answer 2:

大多喜欢@Floris说:

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

现在,你可以打印出来,就像你会与普通字符串。

由于斯卡拉2.10有串插补功能 ,它允许你写的东西,如:

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

但我不认为它是非常可读的(提醒perl的):

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


Answer 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))


文章来源: How can I convert seconds to time in Scala?
标签: scala