我使用此代码获取上一个日期,但我希望获取除Saturday and Sunday
我用来获取上一个日期的代码:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Main {
public static String previousDateString(String dateString)
throws ParseException {
// Create a date formatter using your format string
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
// Parse the given date string into a Date object.
// Note: This can throw a ParseException.
Date myDate = dateFormat.parse(dateString);
// Use the Calendar class to subtract one day
Calendar calendar = Calendar.getInstance();
calendar.setTime(myDate);
calendar.add(Calendar.DAY_OF_YEAR, -1);
// Use the date formatter to produce a formatted date string
Date previousDate = calendar.getTime();
String result = dateFormat.format(previousDate);
return result;
}
public static void main(String[] args) {
String dateString = "2012-08-20";
try {
// This will print 2012-08-19
System.out.println(previousDateString(dateString));
} catch (ParseException e) {
System.out.println("Invalid date string");
e.printStackTrace();
}
}
}`
它工作正常,但需要获得不是星期六或星期日的上一个日期。
此致
答案 0 :(得分:2)
您必须从DAY_OF_WEEK
对象获取 calendar
,如果其next
天为MONDAY
,则减去three
天或SUNDAY
然后从日期/日历对象中减去two
天。
calendar.setTime(myDate);
int dayOfWeek=calendar.get(Calendar.DAY_OF_WEEK);
if(dayOfWeek==Calendar.MONDAY)
calendar.add(Calendar.DAY_OF_YEAR, -3);
else
if(dayOfWeek==Calendar.SUNDAY)
calendar.add(Calendar.DAY_OF_YEAR, -2);
else
calendar.add(Calendar.DAY_OF_YEAR, -1);