我在Scala中发现了一个非常奇怪的问题。我试图去上个月的最后一天。下面的工作表显示了正确的结果(在Scala中,月份从0(一月)开始,因此三月是2)。
但是,如果我注释掉左侧的最后一行,则结果如下:
我所做的只是将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
最佳答案
得到上个月的最后一天
这是你想要的吗?
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