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