Java 当前月份的开始和结束日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3083781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:17:50  来源:igfitidea点击:

Start and end date of a current month

javadate-manipulation

提问by Lalchand

I need the start date and the end date of the current month in Java. When the JSP page is loaded with the current month it should automatically calculate the start and end date of that month. It should be irrespective of the year and month. That is some month has 31 days or 30 days or 28 days. This should satisfy for a leap year too. Can you help me out with that?

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

For example if I select month May in a list box I need starting date that is 1 and end date that is 31.

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

采纳答案by Abhinav Sarkar

There you go:

你去吧:

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: Pairclass is simply a pair of two values.

PS:Pairclass 只是一对两个值。

回答by leonbloy

If you have the option, you'd better avoid the horrid Java Date API, and use instead Jodatime. Here is an example:

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

LocalDate monthBegin = new LocalDate().withDayOfMonth(1);
LocalDate monthEnd = new LocalDate().plusMonths(1).withDayOfMonth(1).minusDays(1);

回答by John O

With the date4jlibrary :

使用date4j库:

dt.getStartOfMonth();
dt.getEndOfMonth();

回答by paks

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;
    }

回答by ManishKr

Making it more modular, you can have one main function that calculates startDate or EndDate and than you can have individual methods to getMonthStartDate, getMonthEndDateand to getMonthStartEndDate. Use methods as per your requirement.

使之更模块化,你可以有计算的startDate或结束日期一个主要功能,比你可以有个人的方法getMonthStartDategetMonthEndDategetMonthStartEndDate。根据您的要求使用方法。

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;
}

回答by manikanta

For Java 8+, below method will given current month first & last dates as LocalDate instances.

对于 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);
}

Side note: Using LocalDate.ofEpochDay(...)instead of LocalDate.now()gives much improved performance. Also, using the millis-in-a-day expression instead of the end value, which is 86400000is performing better. I initially thought the latter would perform better than the the expression :P

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

回答by Phoenix

Try this Code

试试这个代码

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());

Hope it helps.

希望能帮助到你。

回答by Sumeet

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());

回答by aianitro

Try LocalDate from Java 8:

从 Java 8 尝试 LocalDate:

LocalDate today = LocalDate.now();
System.out.println("First day: " + today.withDayOfMonth(1));
System.out.println("Last day: " + today.withDayOfMonth(today.lengthOfMonth()));

回答by suraj singh

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()))
    }