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

问题描述 投票:3回答:3

我在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())

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

scala date simpledateformat
3个回答
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)

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)

3
投票

JSR 310的实现:

import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter

DateTimeFormatter.ISO_INSTANT.format(OffsetDateTime.now().minusDays(1L))
© www.soinside.com 2019 - 2024. All rights reserved.