我需要找到上个月的上周五。这个月是六月。我需要五月的最后一个星期五。在这种情况下(5月29日)。我只能找到当月的上周五。在我找到上个月的星期五之后,我需要检查它已经过了多少天。如果自上周五起已经过了5天,则执行任务。希望这很清楚。如果没有,请询问,我可以更详细地解释。
public class task {
static String lastFriday;
static String dtToday;
public static void main(String[] args) {
//daysInBetween = current day - (last month's friday date)
if (daysInBetween = 5) {
//run program after 5 days
} else { //quit program }
}
// Gets last Friday of the Month
// Need last Friday of previous Month...
public static String getLastFriday() {
Calendar cal = new GregorianCalendar();
cal.set(GregorianCalendar.DAY_OF_WEEK, Calendar.FRIDAY);
cal.set(GregorianCalendar.DAY_OF_WEEK_IN_MONTH, -1);
SimpleDateFormat date_format = new SimpleDateFormat("yyyy/MM/dd");
lastFriday = date_format.format(cal.getTime());
return lastFriday;
}
// Gets today's date
public static String getToday() {
Calendar cal = new GregorianCalendar();
SimpleDateFormat date_format = new SimpleDateFormat("yyyy/MM/dd");
dtToday = date_format.format(cal.getTime());
return dtToday;
}
}
答案 0 :(得分:2)
使用方法
查找last Friday of any monthpublic Date getLastFriday( int month, int year ) {
Calendar cal = Calendar.getInstance();
cal.set( year, month + 1, 1 );
cal.add( Calendar.DAY_OF_MONTH, -( cal.get( Calendar.DAY_OF_WEEK ) % 7 + 1 ) );
return cal.getTime();
}
您可以使用以下方法查找2天之间的差异 -
public int getDifferenceDays(Date d1, Date d2) {
int daysdiff=0;
long diff = d2.getTime() - d1.getTime();
long diffDays = diff / (24 * 60 * 60 * 1000)+1;
daysdiff = (int) diffDays;
return daysdiff;
}
答案 1 :(得分:0)
你快到了,只需在你的getLastFriday
方法中添加以下内容:
// Gets last Friday of the Month
// Need last Friday of previous Month...
public static String getLastFriday() {
Calendar cal = new GregorianCalendar();
// reduce the "current" month by 1 to get the "previous" month
cal.set(GregorianCalendar.MONTH, cal.get(GregorianCalendar.MONTH) - 1);
cal.set(GregorianCalendar.DAY_OF_WEEK, Calendar.FRIDAY);
cal.set(GregorianCalendar.DAY_OF_WEEK_IN_MONTH, -1);
SimpleDateFormat date_format = new SimpleDateFormat("yyyy/MM/dd");
lastFriday = date_format.format(cal.getTime());
return lastFriday;
}
然后,您可以阅读其中一个问题及其答案,以便在几天内获得差异:Finding days difference in java或Calculating the difference between two Java date instances。