我有一个带有天名称的字符串,我只想看看那几天的字符串,那是即将到来的一天。
例如,字符串包含“ Sun,Mon,Tue,Fri,Sat”
如果今天是星期三,则只能返回星期五。
有人知道如何执行此操作吗?
目前我正在做这件事,但尽管星期天已经过去,但它似乎也要返回太阳。
static String[] strDays = new String[] { "Sun", "Mon", "Tue", "Wed", "Thu",
"Fri", "Sat" };
String nexday="sun,mon,tue,fri,sat";
String nexdayone[] = nexday.split(",");
Calendar now = Calendar.getInstance();
Calendar futurecal = Calendar.getInstance();
for (int i = 0; i < nexdayone.length; i++) {
for (int j = 0; j < 7; j++) {
if (strDays[j].equalsIgnoreCase(nexdayone[i])) {
futurecal.set(Calendar.DAY_OF_WEEK, j);
if (futurecal.after(now)) {
Log.d(now.get(Calendar.DAY_OF_WEEK)+" --after-- "+j,""+strDays[j]);
break;
}
}
}
}
最佳答案
使用SortedSet查找第二天的解决方案。
private static SimpleDateFormat fmt = new SimpleDateFormat("E");
public static void main(String[] args) throws Exception {
// Put the days in the list into a sorted set
TreeSet<Integer> daySet = new TreeSet<Integer>();
for (String day : "Sun,Mon,Tue,Fri,Sat".split(",")) {
daySet.add(dayOfWeek(day));
}
// Find the next day in the list, starting from today
Calendar cal = Calendar.getInstance();
int today = cal.get(Calendar.DAY_OF_WEEK);
cal.set(Calendar.DAY_OF_WEEK, findNext(daySet, today));
System.out.println(fmt.format(cal.getTime()));
}
/**
* Parses a day name, and returns the number of the day in the week.
*/
private static int dayOfWeek(String day) {
Calendar cal = Calendar.getInstance();
cal.setTime(fmt.parse(day, new ParsePosition(0)));
return cal.get(Calendar.DAY_OF_WEEK);
}
/**
* Finds a value in the sorted set that is greater than 'from'.
* If there are no greater values, return the first value.
*/
private static int findNext(SortedSet<Integer> set, int from) {
SortedSet<Integer> tail = set.tailSet(Integer.valueOf(from));
return tail.isEmpty() ? set.first() : tail.first();
}
假设今天是星期二。我不确定是星期二还是星期五返回。上面的解决方案将显示“ Tue”。如果您需要“星期五”,即第二天(今天不是今天),则可以使用:
Integer.valueOf(from + 1)
中的findNext
。关于java - 如何使用Java判断一天是否过去,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13491365/