我想获取给定星期数的开始和结束日期。我尝试了以下代码,但始终返回相同的日期(当前星期)
val c: Calendar = Calendar.getInstance()
val week = 39
c.set(Calendar.WEEK_OF_YEAR, week)
val firstDayOfWeek = c.firstDayOfWeek
c.set(Calendar.DAY_OF_WEEK,firstDayOfWeek)
startDate = SimpleDateFormat("yyyy-MM-dd",Locale.getDefault()).format(c.time).toString()
c.set(Calendar.DAY_OF_WEEK, firstDayOfWeek+6)
endDate = SimpleDateFormat("yyyy-MM-dd",Locale.getDefault()).format(c.time).toString()
答案 0 :(得分:0)
我通过在使用前多拨c.time
来解决它。这是工作代码:
val c: Calendar = Calendar.getInstance()//Locale.getDefault())
val week = 39
c.set(Calendar.WEEK_OF_YEAR, week)
val t = c.time;
val firstDay = c.firstDayOfWeek
c.set(Calendar.DAY_OF_WEEK,firstDay)
startDate = SimpleDateFormat("yyyy-MM-dd",Locale.getDefault()).format(c.time).toString()
c.set(Calendar.DAY_OF_WEEK,firstDay+6)
endDate = SimpleDateFormat("yyyy-MM-dd",Locale.getDefault()).format(c.time).toString()
无法理解其工作原理,请阅读此https://developer.android.com/reference/java/util/Calendar#field-manipulation
后尝试答案 1 :(得分:0)
您必须丢失某些东西或犯一些基本错误。以下是证明:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
int week = 39;
Calendar c = Calendar.getInstance();
c.set(Calendar.WEEK_OF_YEAR, week);
int firstDayOfWeek = c.getFirstDayOfWeek();
// Start date
c.set(Calendar.DAY_OF_WEEK, firstDayOfWeek);
String startDate = sdf.format(c.getTime());
System.out.println(startDate);
// End date
c.set(Calendar.DAY_OF_WEEK, firstDayOfWeek + 6);
String endDate = sdf.format(c.getTime());
System.out.println(endDate);
}
}
输出:
2020-09-21
2020-09-27
注意::我不了解Kotlin,但不了解AFAIK,您也可以在Kotlin中运行Java代码。如果您想坚持使用Kotlin语法,希望您能够轻松将其转换为Kotlin语法。