gpt4 book ai didi

java - 如何在Android中获得一个月的日子

转载 作者:行者123 更新时间:2023-12-02 13:40:59 25 4
gpt4 key购买 nike

我有客户UI日历,我有一个问题:
例如,9月从01/09 / 2020-> 30/09/2020开始30天,但UI日历显示从29/08 / 2020-> 02/10/2020开始
这是我的代码。谁能帮我?

 val calendar: Calendar =  Calendar.getInstance()       
calendar.firstDayOfWeek = Calendar.MONDAY
calendar.add(Calendar.MONTH, position)

// Set day of month as 1
calendar.set(Calendar.DAY_OF_MONTH, 1)

// Get a number of the first day of the week
val dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK)

// Count when month is beginning
val firstDayOfWeek = calendar.firstDayOfWeek
val monthBeginningCell = (if (dayOfWeek < firstDayOfWeek) 7 else 0) + dayOfWeek - firstDayOfWeek

// Subtract a number of beginning days, it will let to load a part of a previous month
calendar.add(Calendar.DAY_OF_MONTH, -monthBeginningCell)

/* Get all days of one page (35 is a number of all possible cells in one page
(a part of previous month, current month and a part of next month))
*/
while (days.size < 35) {
days.add(calendar.time)
calendar.add(Calendar.DAY_OF_MONTH, 1)
}

最佳答案

您到底需要什么?如果您需要一个月的全部日历,则可以使用以下代码作为示例:

class Scratch {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
// The month you want to set
int month = Calendar.SEPTEMBER;
calendar.set(Calendar.MONTH, month);
int firstDayOfMonth = calendar.getActualMinimum(Calendar.DAY_OF_MONTH);
int lastDayOfMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println(getTimeOfWeek(lastDayOfMonth, false, month));
System.out.println(getTimeOfWeek(firstDayOfMonth, true, month));
}

private static Instant getTimeOfWeek(int day, boolean isFirst, int month) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, day);
int dayInWeek = calendar.get(Calendar.DAY_OF_WEEK);
if (isFirst) {
calendar.set(Calendar.DAY_OF_MONTH, day - dayInWeek + 1);
} else {
calendar.set(Calendar.DAY_OF_MONTH, day + 7 - dayInWeek);
}
return calendar.toInstant();
}
}
如果您只想要该月的范围,只需将日历设置为该月的第一天和最后一天。
希望它能起作用!

关于java - 如何在Android中获得一个月的日子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63461149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com