44

我需要Java中当月的开始日期和结束日期。当 JSP 页面加载当前月份时,它应该自动计算该月的开始和结束日期。它应该与年份和月份无关。即某个月有 31 天或 30 天或 28 天。这也应该满足闰年。你能帮我解决这个问题吗?

例如,如果我在列表框中选择月份 May,我需要开始日期为 1,结束日期为 31。

4

14 回答 14

69

你去:

public Pair<Date, Date> getDateRange() {
    Date begining, end;

    {
        Calendar calendar = getCalendarForNow();
        calendar.set(Calendar.DAY_OF_MONTH,
                calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
        setTimeToBeginningOfDay(calendar);
        begining = calendar.getTime();
    }

    {
        Calendar calendar = getCalendarForNow();
        calendar.set(Calendar.DAY_OF_MONTH,
                calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        setTimeToEndofDay(calendar);
        end = calendar.getTime();
    }

    return Pair.of(begining, end);
}

private static Calendar getCalendarForNow() {
    Calendar calendar = GregorianCalendar.getInstance();
    calendar.setTime(new Date());
    return calendar;
}

private static void setTimeToBeginningOfDay(Calendar calendar) {
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
}

private static void setTimeToEndofDay(Calendar calendar) {
    calendar.set(Calendar.HOUR_OF_DAY, 23);
    calendar.set(Calendar.MINUTE, 59);
    calendar.set(Calendar.SECOND, 59);
    calendar.set(Calendar.MILLISECOND, 999);
}

PS:Pair类只是一对两个值。

于 2010-06-21T10:23:24.603 回答
32

如果可以选择,最好避免使用可怕的 Java Date API,而改用Jodatime。这是一个例子:

LocalDate monthBegin = new LocalDate().withDayOfMonth(1);
LocalDate monthEnd = new LocalDate().plusMonths(1).withDayOfMonth(1).minusDays(1);
于 2010-06-21T11:39:49.703 回答
17

尝试 Java 8 中的 LocalDate:

LocalDate today = LocalDate.now();
System.out.println("First day: " + today.withDayOfMonth(1));
System.out.println("Last day: " + today.withDayOfMonth(today.lengthOfMonth()));
于 2016-10-27T04:42:11.757 回答
8

简单而最好的,试试这个

Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MONTH, 0);
            calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
            Date monthFirstDay = calendar.getTime();
            calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
            Date monthLastDay = calendar.getTime();

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String startDateStr = df.format(monthFirstDay);
        String endDateStr = df.format(monthLastDay);

        Log.e("DateFirstLast",startDateStr+" "+endDateStr);
于 2019-09-21T06:52:00.467 回答
5
Calendar c = Calendar.getInstance();
    int year = c.get(Calendar.YEAR);
    int month = c.get(Calendar.MONTH);
    int day = 1;
    c.set(year, month, day);
    int numOfDaysInMonth = c.getActualMaximum(Calendar.DAY_OF_MONTH);
    System.out.println("First Day of month: " + c.getTime());
    c.add(Calendar.DAY_OF_MONTH, numOfDaysInMonth-1);
    System.out.println("Last Day of month: " + c.getTime());
于 2016-01-21T07:03:30.800 回答
4

使用date4j库:

dt.getStartOfMonth();
dt.getEndOfMonth();
于 2011-02-13T02:56:06.967 回答
3

试试这个代码

Calendar calendar = Calendar.getInstance();
int yearpart = 2010;
int monthPart = 11;
int dateDay = 1;
calendar.set(yearpart, monthPart, dateDay);
int numOfDaysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println("Number of Days: " + numOfDaysInMonth);
System.out.println("First Day of month: " + calendar.getTime());
calendar.add(Calendar.DAY_OF_MONTH, numOfDaysInMonth-1);
System.out.println("Last Day of month: " + calendar.getTime());

希望能帮助到你。

于 2015-09-04T13:30:59.127 回答
2

如果你有java.time.YearMonth你可以这样做:

YearMonth startYearMonth = YearMonth.now();
java.time.LocalDate startOfMonthDate = startYearMonth.atDay(1);    
java.time.LocalDate endOfMonthDate   = startYearMonth.atEndOfMonth();
于 2021-08-29T20:52:28.503 回答
1
Date begining, ending;
Calendar calendar_start =BusinessUnitUtility.getCalendarForNow();
  calendar_start.set(Calendar.DAY_OF_MONTH,calendar_start.getActualMinimum(Calendar.DAY_OF_MONTH));
  begining = calendar_start.getTime();
  String start= DateDifference.dateToString(begining,"dd-MMM-yyyy");//sdf.format(begining);


   //            for End Date of month
  Calendar calendar_end = BusinessUnitUtility.getCalendarForNow();
  calendar_end.set(Calendar.DAY_OF_MONTH,calendar_end.getActualMaximum(Calendar.DAY_OF_MONTH));
      ending = calendar_end.getTime();
      String end=DateDifference.dateToString(ending,"dd-MMM-yyyy");//or sdf.format(end);

enter code here



public static Calendar getCalendarForNow() {
        Calendar calendar = GregorianCalendar.getInstance();
        calendar.setTime(new Date());
        return calendar;
    }
于 2011-04-06T10:00:49.233 回答
0

对于 Java 8+,以下方法将给出当前月份的第一个和最后一个日期作为 LocalDate 实例。

public static LocalDate getCurrentMonthFirstDate() {
    return LocalDate.ofEpochDay(System.currentTimeMillis() / (24 * 60 * 60 * 1000) ).withDayOfMonth(1);
}

public static LocalDate getCurrentMonthLastDate() {
    return LocalDate.ofEpochDay(System.currentTimeMillis() / (24 * 60 * 60 * 1000) ).plusMonths(1).withDayOfMonth(1).minusDays(1);
}

旁注:使用LocalDate.ofEpochDay(...)代替可以LocalDate.now()大大提高性能。此外,使用millis-in-a-day 表达式而不是最终值,它86400000的性能更好。我最初认为后者会比表达式表现更好:P

于 2015-04-29T18:16:39.410 回答
0

获取该月的第一天和最后一天的一个非常简单的步骤:

    Calendar calendar = Calendar.getInstance();
    
    // Get the current date
    Date today = calendar.getTime();
    
    
    // Setting the first day of month
    calendar.set(Calendar.DAY_OF_MONTH, 1);
    Date firstDayOfMonth = calendar.getTime();

    // Move to next month  
    calendar.add(Calendar.MONTH, 1);
    // setting the 1st day of the month
    calendar.set(Calendar.DAY_OF_MONTH, 1);
    // Move a day back from the date
    calendar.add(Calendar.DATE, -1);
    Date lastDayOfMonth = calendar.getTime();

    // Formatting the date  
    DateFormat sdf = new SimpleDateFormat("dd-MMM-YY");

    String todayStr = sdf.format(today);
    String firstDayOfMonthStr = sdf.format(firstDayOfMonth);
    String lastDayOfMonthStr = sdf.format(lastDayOfMonth);
    
    System.out.println("Today            : " + todayStr);
    System.out.println("Fist Day of Month: "+firstDayOfMonthStr);
    System.out.println("Last Day of Month: "+lastDayOfMonthStr);
于 2021-08-26T09:33:29.750 回答
0

您可以按如下方式实现它:

public void FirstAndLastDate() {

    SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");
    //start date of month
    calendarStart = Calendar.getInstance();
    calendarStart.set(Integer.parseInt((new SimpleDateFormat("yyyy")).format(new Date().getTime()))
            , Integer.parseInt((new SimpleDateFormat("MM")).format(new Date().getTime()))
            , Calendar.getInstance().getActualMinimum(Calendar.DAY_OF_MONTH));

    //End Date of month
    calendarEnd = Calendar.getInstance();
    calendarEnd.set(Integer.parseInt((new SimpleDateFormat("yyyy")).format(new Date().getTime()))
            , Integer.parseInt((new SimpleDateFormat("MM")).format(new Date().getTime()))
            , Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH));

    Toast.makeText(this, sdf.format(calendarStart.getTime()) + "\n" + sdf.format(calendarEnd.getTime()), Toast.LENGTH_SHORT).show();

}
于 2019-11-10T16:10:38.593 回答
0
public static void main(String[] args) 
    {
        LocalDate today = LocalDate.now();
        System.out.println("First day: " + 
today.withDayOfMonth(1));
        System.out.println("Last day: " + today.withDayOfMonth(today.lengthOfMonth()))
    }
于 2019-06-07T11:11:44.107 回答
-1

使其更加模块化,您可以拥有一个计算 startDate 或 EndDate 的主要函数,而不是您可以拥有单独的方法 togetMonthStartDategetMonthEndDateto getMonthStartEndDate。根据您的要求使用方法。

public static String getMonthStartEndDate(){
    String start = getMonthDate("START");
    String end = getMonthDate("END");
    String result = start + " to " + end;
    return result;
}

public static String getMonthStartDate(){
    String start = getMonthDate("START");
    return start;
}

public static String getMonthEndDate(){
    String end = getMonthDate("END");
    return end;
}

/**
 * @param filter 
 * START for start date of month e.g.  Nov 01, 2013
 * END for end date of month e.g.  Nov 30, 2013
 * @return
 */
public static String getMonthDate(String filter){
            String MMM_DD_COMMA_YYYY       = "MMM dd, yyyy";
    SimpleDateFormat sdf = new SimpleDateFormat(MMM_DD_COMMA_YYYY);
    sdf.setTimeZone(TimeZone.getTimeZone("PST"));
    sdf.format(GregorianCalendar.getInstance().getTime());

    Calendar cal =  GregorianCalendar.getInstance();
    int date = cal.getActualMinimum(Calendar.DATE);
    if("END".equalsIgnoreCase(filter)){
        date = cal.getActualMaximum(Calendar.DATE);
    }
    cal.set(Calendar.DATE, date);
    String result =  sdf.format(cal.getTime());
    System.out.println(" " + result  );

    return result;
}
于 2013-11-17T07:58:45.483 回答