如何使用Scala设置昨天的日期?

时间:2018-02-15 14:38:57

标签: scala date simpledateformat

我正在Scala中创建一个日期。

  val dafo = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'")
  val tz = TimeZone.getTimeZone("UTC")
  dafo.setTimeZone(tz)
  val endTime = dafo.format(new Date())

如何设定昨天的日期而不是今天的日期?

4 个答案:

答案 0 :(得分:4)

以下是使用java.time

获取昨天日期/时间并对其进行格式化的方法
import java.time.{ZonedDateTime, ZoneId}
import java.time.format.DateTimeFormatter


val yesterday = ZonedDateTime.now(ZoneId.of("UTC")).minusDays(1)
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm'Z'")
val result = formatter format yesterday

println(result)

答案 1 :(得分:3)

您可以使用日历:

val dafo = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'")
val tz = TimeZone.getTimeZone("UTC")
dafo.setTimeZone(tz)

val calendar = Calendar.getInstance()
calendar.add(Calendar.DATE, -1)
dafo.format(calendar.getTime)

答案 2 :(得分:3)

JSR-310实施:

"engines": {
"node": "9.4.0",
"npm": "5.6.0" 
}

答案 3 :(得分:1)

这是另一种替代解决方案。我认为它是一个更清洁的版本。

val today = java.time.LocalDate.now

today: java.time.LocalDate = 2019-12-10

val yesterday= java.time.LocalDate.now.minusDays(1)

yesterday: java.time.LocalDate = 2019-12-09