'A Scala current date/time example'에 해당되는 글 1건

  1. 2014.03.28 A Scala current date/time example
00.scala2014. 3. 28. 12:55
반응형

Scala date/time FAQ: How do I get the current date and time in Scala?

The following code demonstrates how to get the current time in Scala, and then further shows how to get other information, such as the current minute, using the Java SimpleDateFormat class:

def onTheFives :Boolean = {
  val today = Calendar.getInstance().getTime()
  val minuteFormat = new SimpleDateFormat("mm")
  val currentMinuteAsString = minuteFormat.format(today)
  try {
    val currentMinute = Integer.parseInt(currentMinuteAsString)
    if (currentMinute % 5 == 0) return true
    else return false
  } catch {
    case _ => return false
  }
}

As you can see, you get the current time in Scala with this line of code:

val today = Calendar.getInstance().getTime()

This uses the Java Calendar class, which you'll have to import into your Scala application.

I later get the "current minute" from the current time object using the Java SimpleDateFormat class using these lines of code:

val minuteFormat = new SimpleDateFormat("mm")
val currentMinuteAsString = minuteFormat.format(today)

One problem with this approach is that the minute comes back as a String, which can be something like "01". Because I'm trying to get my computer to speak the current time to me, I don't want that leading zero, so I convert the String to an Int using the code shown in the try/catch brackets.

Getting the current hour in Scala

On a related note, if you want to get the current hour in Scala, you can use this very similar method:

def getCurrentHour: String = {
  val today = Calendar.getInstance().getTime()
  val hourFormat = new SimpleDateFormat("hh")
  try {
    // returns something like "01" if i just return at this point, so cast it to
    // an int, then back to a string (or return the leading '0' if you prefer)
    val currentHour = Integer.parseInt(hourFormat.format(today))
    return "" + currentHour
  } catch {
    // TODO return Some/None/Whatever
    case _ => return "0"
  }
  return hourFormat.format(today)
}

This code returns the current hour as a String. (I'm sure there are probably better ways to write this, but my writing time for today is up, so I'll have to leave the code like this for now.)

More Scala SimpleDateFormat examples

On a related note I'll share the following Scala code, which shows a few more SimpleDateFormat examples:

val today = Calendar.getInstance().getTime()
    
// create the date/time formatters
val minuteFormat = new SimpleDateFormat("mm")
val hourFormat = new SimpleDateFormat("hh")
val amPmFormat = new SimpleDateFormat("a")

val currentHour = hourFormat.format(today)      // 12
val currentMinute = minuteFormat.format(today)  // 29
val amOrPm = amPmFormat.format(today)           // PM


Posted by 1010