我需要将日历设置为下周的星期一。我的代码可在Android 9.0上运行,但在Android 6.0上只能在调试时运行。
Calendar.set(..)函数存在问题,它们只是不起作用。例如calendar.set(Calendar.WEEK_OF_YEAR,17)不会将日历周更改为17,但是在调试时它将更改为17。
这是我的代码:
Calendar mcurrentTime = Calendar.getInstance(Locale.GERMANY);
if(AppHelper.getInstance().getNextWeek() != 0){
mcurrentTime.set(Calendar.WEEK_OF_YEAR,
AppHelper.getInstance().getNextWeek());
mcurrentTime.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
}
weekNumberTv.setText(mcurrentTime.get(Calendar.WEEK_OF_YEAR)+"");
Android 9.0 weekNumberTv显示17
Android 6.0 weekNumberTv显示16
如果启动调试模式
Android 6.0 weekNumberTv显示17
答案 0 :(得分:1)
可悲的是,要在7.0之前的版本中进行时间计算,您将不得不使用JavaTime软件包或其反向端口。
实施ThreeTen Android Backport库:
implementation 'com.jakewharton.threetenabp:threetenabp:1.2.0'
https://github.com/JakeWharton/ThreeTenABP
然后在onCreate方法中对其进行初始化。
AndroidThreeTen.init(this)
请确保包含了这些库,而不是Java 8。
import org.threeten.bp.LocalDate
import org.threeten.bp.temporal.ChronoUnit
import org.threeten.bp.temporal.WeekFields
import com.jakewharton.threetenabp.AndroidThreeTen
代码以完成工作
var mCurrentTime = LocalDate.now()
val weekFields = WeekFields.of(Locale.GERMANY)
val currentDayOfWeek = mCurrentTime.get(weekFields.dayOfWeek())
//subtract day of week to monday
mCurrentTime=mCurrentTime.minus((currentDayOfWeek.toLong()-1),ChronoUnit.DAYS)
//add week starting from monday
mCurrentTime=mCurrentTime.plus(1,ChronoUnit.WEEKS)
//get weekOfYear
val weekOfCurrentTime=mCurrentTime.get(weekFields.weekOfYear())
show_week_in_year.text=weekOfCurrentTime.toString()
对不起Kotlin。 Java正在度假。