我正在开发一个项目,其中要求将日期计算为给定月份的最后一个星期五。我想我有一个只使用标准Java的解决方案,但我想知道是否有人知道更简洁或更有效的东西。以下是我今年测试的内容:
for (int month = 0; month < 13; month++) {
GregorianCalendar d = new GregorianCalendar();
d.set(d.MONTH, month);
System.out.println("Last Week of Month in " + d.getDisplayName(d.MONTH, Calendar.LONG, Locale.ENGLISH) + ": " + d.getLeastMaximum(d.WEEK_OF_MONTH));
d.set(d.DAY_OF_WEEK, d.FRIDAY);
d.set(d.WEEK_OF_MONTH, d.getActualMaximum(d.WEEK_OF_MONTH));
while (d.get(d.MONTH) > month || d.get(d.MONTH) < month) {
d.add(d.WEEK_OF_MONTH, -1);
}
Date dt = d.getTime();
System.out.println("Last Friday of Last Week in " + d.getDisplayName(d.MONTH, Calendar.LONG, Locale.ENGLISH) + ": " + dt.toString());
}
答案 0 :(得分:34)
让Calendar.class为你做出魔力;)
pCal.set(GregorianCalendar.DAY_OF_WEEK,Calendar.FRIDAY);
pCal.set(GregorianCalendar.DAY_OF_WEEK_IN_MONTH, -1);
答案 1 :(得分:25)
基于marked23's建议:
public 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 :(得分:9)
你永远不需要循环来找到它。要确定本月的“上周五”日期,请从下个月的第一天开始。减去适当的天数,具体取决于每月第一天的某一天(数字)日期。这是你的“上周五”。我很确定它可以归结为一个冗长的单行,但我不是一个java开发者。所以我会把它留给别人。
答案 3 :(得分:9)
使用Java 8及更高版本中内置的java.time库,您可以使用TemporalAdjusters.lastInMonth
:
val now = LocalDate.now()
val lastInMonth = now.with(TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY))
您可以从DayOfWeek
枚举中选择任何一天。
如果您需要添加时间信息,可以使用任何可用的LocalDate
到LocalDateTime
转换,例如
lastFriday.atStartOfDay() // e.g. 2015-11-27T00:00
答案 4 :(得分:7)
我会使用像Jodatime这样的库。它有一个非常有用的API,它使用正常的月份数。最重要的是,它是线程安全的。
我认为你可以有一个解决方案(但可能不是最短的,但肯定更具可读性):
DateTime now = new DateTime();
DateTime dt = now.dayOfMonth().withMaximumValue().withDayOfWeek(DateTimeConstants.FRIDAY);
if (dt.getMonthOfYear() != now.getMonthOfYear()) {
dt = dt.minusDays(7);
}
System.out.println(dt);
答案 5 :(得分:2)
您需要了解两件事 - 本月的天数以及本月的第一天的工作日。
如果该月的第一天是
只有三种特殊情况。一个switch语句和三个if语句(如果你喜欢每个case都有一行三元运算符......)
在纸上解决问题。不需要任何特殊的库,函数,朱利安转换等(好吧,除了让第一个工作日落下,也许那个月的天数......)
- 亚当
答案 6 :(得分:2)
public static int getLastFriday(int month, int year)
{
Calendar cal = Calendar.getInstance();
cal.set(year, month, 1, 0, 0, 0); // set to first day of the month
cal.set(Calendar.MILLISECOND, 0);
int firstDay = cal.get(Calendar.DAY_OF_WEEK);
int daysOfMonth = cal.getMaximum(Calendar.DAY_OF_MONTH);
switch (firstDay)
{
case Calendar.SUNDAY :
return 27;
case Calendar.MONDAY :
return 26;
case Calendar.TUESDAY :
return 25;
case Calendar.WEDNESDAY :
if (daysOfMonth == 31) return 31;
return 24;
case Calendar.THURSDAY :
if (daysOfMonth >= 30) return 30;
return 23;
case Calendar.FRIDAY :
if (daysOfMonth >= 29) return 29;
return 22;
case Calendar.SATURDAY :
return 28;
}
throw new RuntimeException("what day of the month?");
}}
答案 7 :(得分:1)
稍微容易阅读,蛮力方法:
public int getLastFriday(int month, int year) {
Calendar cal = Calendar.getInstance();
cal.set(year, month, 1, 0, 0, 0); // set to first day of the month
cal.set(Calendar.MILLISECOND, 0);
int friday = -1;
while (cal.get(Calendar.MONTH) == month) {
if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) { // is it a friday?
friday = cal.get(Calendar.DAY_OF_MONTH);
cal.add(Calendar.DAY_OF_MONTH, 7); // skip 7 days
} else {
cal.add(Calendar.DAY_OF_MONTH, 1); // skip 1 day
}
}
return friday;
}
答案 8 :(得分:1)
虽然我同意scubabbl,但这是一个没有内在的版本。
int year = 2008;
for (int m = Calendar.JANUARY; m <= Calendar.DECEMBER; m++) {
Calendar cal = new GregorianCalendar(year, m, 1);
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
int diff = Calendar.FRIDAY - cal.get(Calendar.DAY_OF_WEEK);
if (diff > 0) {
diff -= 7;
}
cal.add(Calendar.DAY_OF_MONTH, diff);
System.out.println(cal.getTime());
}
答案 9 :(得分:1)
这是如何获得本月的最后一个星期五或任何工作日:
Calendar thisMonth = Calendar.getInstance();
dayOfWeek = Calendar.FRIDAY; // or whatever
thisMonth.set(Calendar.WEEK_OF_MONTH, thisMonth.getActualMaximum(Calendar.WEEK_OF_MONTH);;
thisMonth.set(Calendar.DAY_OF_WEEK, dayOfWeek);
int lastDay = thisMonth.get(Calendar.DAY_OF_MONTH); // this should be it.
答案 10 :(得分:1)
以下节目是每个月的最后一个星期五。它可以用来获取任何一个月中任何一天的最后一天。变量offset=0
表示当前月份(系统日期),偏移量= 1表示下个月,依此类推。 getLastFridayofMonth(int offset)
方法将在上周五返回。
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class LastFriday {
public static Calendar getLastFriday(Calendar cal,int offset){
int dayofweek;//1-Sunday,2-Monday so on....
cal.set(Calendar.MONTH,cal.get(Calendar.MONTH)+offset);
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); //set calendar to last day of month
dayofweek=cal.get(Calendar.DAY_OF_WEEK); //get the day of the week for last day of month set above,1-sunday,2-monday etc
if(dayofweek<Calendar.FRIDAY) //Calendar.FRIDAY will return integer value =5
cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH)-7+Calendar.FRIDAY-dayofweek);
else
cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH)+Calendar.FRIDAY-dayofweek);
return cal;
}
public static String getLastFridayofMonth(int offset) { //offset=0 mean current month
final String DATE_FORMAT_NOW = "dd-MMM-yyyy";
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
cal=getLastFriday(cal,offset);
return sdf.format(cal.getTime());
}
public static void main(String[] args) {
System.out.println(getLastFridayofMonth(0)); //0 = current month
System.out.println(getLastFridayofMonth(1));//1=next month
System.out.println(getLastFridayofMonth(2));//2=month after next month
}
}
答案 11 :(得分:1)
在Java 8中,我们可以简单地这样做:
LocalDate lastFridayOfMonth = LocalDate
.now()
.with(lastDayOfMonth())
.with(previous(DayOfWeek.FRIDAY));
答案 12 :(得分:0)
这看起来是完全可以接受的解决方案。如果可行,请使用它。这是最小的代码,除非必须,否则没有理由对其进行优化。
答案 13 :(得分:0)
希望这会有所帮助..
public static void getSundaysInThisMonth(int monthNumber, int yearNumber){
//int year =2009;
//int dayOfWeek = Calendar.SUNDAY;
// instantiate Calender and set to first Sunday of 2009
Calendar cal = new GregorianCalendar();
cal.set(Calendar.MONTH, monthNumber-1);
cal.set(Calendar.YEAR, yearNumber);
cal.set(Calendar.DATE, 1);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
int dateOfWeek = cal.get(Calendar.DATE);
while (dayOfWeek != Calendar.SUNDAY) {
cal.set(Calendar.DATE, ++dateOfWeek);
dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
}
cal.set(Calendar.DATE, dateOfWeek);
int i = 1;
while (cal.get(Calendar.YEAR) == yearNumber && cal.get(Calendar.MONTH)==monthNumber-1)
{
System.out.println("Sunday " + " " + i + ": " + cal.get(Calendar.DAY_OF_MONTH));
cal.add(Calendar.DAY_OF_MONTH, 7);
i++;
}
}
public static void main(String args[]){
getSundaysInThisMonth(1,2009);
}
答案 14 :(得分:0)
public static int lastSundayDate()
{
Calendar cal = getCalendarInstance();
cal.setTime(new Date(getUTCTimeMillis()));
cal.set( Calendar.DAY_OF_MONTH , 25 );
return (25 + 8 - (cal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY ? cal.get(Calendar.DAY_OF_WEEK) : 8));
}
答案 15 :(得分:-1)
public static Calendar getNthDow(int month, int year, int dayOfWeek, int n) {
Calendar cal = Calendar.getInstance();
cal.set(year, month, 1);
cal.set(Calendar.DAY_OF_WEEK, dayOfWeek);
cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, n);
return (cal.get(Calendar.MONTH) == month) && (cal.get(Calendar.YEAR) == year) ? cal : null;
}