什么是小写"月"在Scala中意味着什么?

时间:2018-04-25 21:06:31

标签: java scala datetime

我在Scala中发现了一个非常奇怪的问题。我试图获得上个月的最后一天。以下工作表显示了正确的结果(在Scala中,Month从0(Jan)开始,因此Mar.是2)。

enter image description here

但是,如果我注释掉左边的最后一行,结果如下:

enter image description here

我所做的只是将lastMonth变量分配给month。并且lastMonth更改为3!

我哪里做错了?

以下是代码段:

import java.util.{Calendar, GregorianCalendar} // Get current time and the last date of last month

val now = Calendar.getInstance()
// test code
//now.set(Calendar.MONTH, Calendar.DECEMBER)

// get current year
val currYear = now.get(Calendar.YEAR)
// get current month, JANUARY is 0
val currMonth = now.get(Calendar.MONTH)

// back to last month
val lastMonthCalendar = now
// if this month is Dec, the YEAR would be automatically deducted by 1
lastMonthCalendar.add(Calendar.MONTH, -1)
lastMonthCalendar.getTime
val lastMonth = lastMonthCalendar.get(Calendar.MONTH)
val numDaysOfLastMonth = lastMonthCalendar.getActualMaximum(Calendar.DAY_OF_MONTH)
lastMonthCalendar.set(Calendar.DATE, numDaysOfLastMonth)
lastMonthCalendar.getTime

var year = lastMonthCalendar.get(Calendar.YEAR)
var month = lastMonth

1 个答案:

答案 0 :(得分:1)

  

获取上个月的最后一天

这是你想要的吗?

scala> import java.time.LocalDate
import java.time.LocalDate

scala>  LocalDate.now().withDayOfMonth(1).minusDays(1)
res1: java.time.LocalDate = 2018-03-31

scala> res1.getDayOfMonth
res2: Int = 31

scala> res1.getMonth
res3: java.time.Month = MARCH

scala> res1.getMonthValue
res4: Int = 3