1
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 形式显示。预先感谢您的任何帮助!

4

3 回答 3

7

我认为答案是

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

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

于 2013-10-01T22:41:49.767 回答
5

就像@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 有字符串插值功能,它允许您编写如下内容:

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

但我认为它的可读性不高(提醒 perl):

val str = f"$h%02d:$m%02d"
于 2013-10-01T22:43:09.847 回答
1
// 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))
于 2016-05-19T09:01:17.237 回答