如何确定Scala中给定日期前一天的日期?

时间:2013-12-30 07:27:44

标签: scala

如何在Scala中实现以下Java段?也就是说,如何确定Scala中给定日期前一天的日期?

Calendar cal = Calendar.getInstance();
cal.setTime(myDate);
cal.add(Calendar.DAY_OF_YEAR,-1);
Date oneDayBefore= cal.getTime();

谢谢。

3 个答案:

答案 0 :(得分:3)

import java.util.Calendar
val cal = Calendar.getInstance()
//cal.setTime(myDate); 
cal.add(Calendar.DAY_OF_YEAR,-1);
val oneDayBefore = cal.getTime();
>>oneDayBefore: java.util.Date = Sun Dec 29 11:52:17 MSK 2013

答案 1 :(得分:3)

首先,您必须知道可以在Scala中导入和使用任何Java API,因此翻译很简单。其次,对于Java和Scala中的日期/时间操作(特别是在Scala中),我建议你采用Joda库。

答案 2 :(得分:2)

对于更多Scala-esque的感觉,您可以使用nscala-time,这是Joda-Time的包装,事实上的非JDK日期实用程序:

import com.github.nscala_time.time.Imports._
import com.github.nscala_time.time.Imports.DateTime._

  //if myDate is DateTime
  val myJodaDate = yesterday
  println( myJodaDate - 1.day )
  //2013-12-28T12:35:22.248Z

  //if myDate is DateTime and only interested in the date(no-time) portion
  println( (myJodaDate - 1.day).toLocalDate )
  //2013-12-28

  //if myDate is java.util.Date and interested in returning java.util.Date too
  val myJavaDate = myJodaDate.toDate
  println( (new DateTime(myJavaDate) - 1.day).toDate )
  //Sat Dec 28 12:39:12 GMT 2013