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形式显示。提前感谢您的帮助!
答案 0 :(得分:6)
答案 1 :(得分:4)
大多数人喜欢@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
现在您可以打印它,就像使用常规字符串一样。
因为scala 2.10有string interpolation feature,所以你可以编写如下内容:
val foo = "bar"
println(s"I'm $foo!")
// I'm bar!
但我认为它不太可读(提醒perl):
val str = f"$h%02d:$m%02d"
答案 2 :(得分:0)
// 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))