75

我的输入字符串日期如下:

String date = "1/13/2012";

我得到的月份如下:

SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date convertedDate = dateFormat.parse(date);
String month = new SimpleDateFormat("MM").format(convertedDate);

但是如何在给定的字符串日期中获取该月的最后一个日历日?

例如:对于字符串"1/13/2012",输出必须是"1/31/2012".

4

16 回答 16

184

Java 8 及更高版本。

通过使用convertedDate.getMonth().length(convertedDate.isLeapYear())whereconvertedDateLocalDate.

String date = "1/13/2012";
LocalDate convertedDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("M/d/yyyy"));
convertedDate = convertedDate.withDayOfMonth(
                                convertedDate.getMonth().length(convertedDate.isLeapYear()));

Java 7 及以下。

通过使用getActualMaximum方法java.util.Calendar

String date = "1/13/2012";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date convertedDate = dateFormat.parse(date);
Calendar c = Calendar.getInstance();
c.setTime(convertedDate);
c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
于 2012-11-29T11:13:45.317 回答
31

这看起来像您的需求:

http://obscuredclarity.blogspot.de/2010/08/get-last-day-of-month-date-object-in.html

代码:

import java.text.DateFormat;  
import java.text.DateFormat;  
import java.text.SimpleDateFormat;  
import java.util.Calendar;  
import java.util.Date;  

//Java 1.4+ Compatible  
//  
// The following example code demonstrates how to get  
// a Date object representing the last day of the month  
// relative to a given Date object.  

public class GetLastDayOfMonth {  

    public static void main(String[] args) {  

        Date today = new Date();  

        Calendar calendar = Calendar.getInstance();  
        calendar.setTime(today);  

        calendar.add(Calendar.MONTH, 1);  
        calendar.set(Calendar.DAY_OF_MONTH, 1);  
        calendar.add(Calendar.DATE, -1);  

        Date lastDayOfMonth = calendar.getTime();  

        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
        System.out.println("Today            : " + sdf.format(today));  
        System.out.println("Last Day of Month: " + sdf.format(lastDayOfMonth));  
    }  

} 

输出:

Today            : 2010-08-03  
Last Day of Month: 2010-08-31  
于 2012-11-29T11:16:18.900 回答
22

通过使用 java 8 java.time.LocalDate

String date = "1/13/2012";
LocalDate lastDayOfMonth = LocalDate.parse(date, DateTimeFormatter.ofPattern("M/dd/yyyy"))
       .with(TemporalAdjusters.lastDayOfMonth());
于 2016-11-19T04:56:29.413 回答
8
于 2019-01-07T19:24:11.683 回答
7

使用 Java 8 DateTime/ LocalDateTime

String dateString = "01/13/2012";
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy", Locale.US); 
LocalDate date = LocalDate.parse(dateString, dateFormat);       
ValueRange range = date.range(ChronoField.DAY_OF_MONTH);
Long max = range.getMaximum();
LocalDate newDate = date.withDayOfMonth(max.intValue());
System.out.println(newDate); 

或者

String dateString = "01/13/2012";
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy", Locale.US); 
LocalDate date = LocalDate.parse(dateString, dateFormat);
LocalDate newDate = date.withDayOfMonth(date.getMonth().length(date.isLeapYear()));
System.out.println(newDate);

输出:

2012-01-31

LocalDateTimeLocalDate如果您的日期字符串中有时间信息,则应该使用它。IE2015/07/22 16:49

于 2015-07-30T09:39:46.103 回答
6

Java 8 及更高版本:

import java.time.LocalDate;
import java.time.Year;

static int lastDayOfMonth(int Y, int M) {
    return LocalDate.of(Y, M, 1).getMonth().length(Year.of(Y).isLeap());
}

以 Basil Bourque 的评论为准

import java.time.YearMonth;

int lastDayOfMonth = YearMonth.of(Y, M).lengthOfMonth();
于 2019-01-07T12:33:21.593 回答
3

最简单的方法是构造一个新GregorianCalendar实例,见下文:

Calendar cal = new GregorianCalendar(2013, 5, 0);
Date date = cal.getTime();
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Date : " + sdf.format(date));

输出:

Date : 2013-05-31

注意力:

month 用于设置日历中 MONTH 日历字段的值。月份值是基于 0 的,例如 0 表示一月。

于 2013-08-09T05:35:49.330 回答
1

您可以使用以下代码获取该月的最后一天

public static String getLastDayOfTheMonth(String date) {
        String lastDayOfTheMonth = "";

        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
        try{
        java.util.Date dt= formatter.parse(date);
        Calendar calendar = Calendar.getInstance();  
        calendar.setTime(dt);  

        calendar.add(Calendar.MONTH, 1);  
        calendar.set(Calendar.DAY_OF_MONTH, 1);  
        calendar.add(Calendar.DATE, -1);  

        java.util.Date lastDay = calendar.getTime();  

        lastDayOfTheMonth = formatter.format(lastDay);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return lastDayOfTheMonth;
    }
于 2016-06-29T13:30:11.897 回答
1
            String givenStringDate ="07/16/2020";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
        java.util.Date convertedUtillDate;
            /*
             * If your output requirement is in LocalDate format use below snippet
             * 
             */
            LocalDate localDate =LocalDate.parse(givenStringDate, formatter);
            LocalDate localDateLastDayOfMonth = localDate.with(TemporalAdjusters.lastDayOfMonth());

            /*
             * If your output requirement is in Calendar format use below snippet
             * 
             */
            convertedUtillDate = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
            Calendar calendarLastDayOfMonth = Calendar.getInstance();
            calendarLastDayOfMonth.setTime(convertedUtillDate);
            int lastDate = calendarLastDayOfMonth.getActualMaximum(Calendar.DATE);
            calendarLastDayOfMonth.set(Calendar.DATE, lastDate);

在 Java 1.8 中测试。我希望这会对某人有所帮助。

于 2020-05-26T12:16:11.640 回答
0

我认为最简单和最快的方法是

public static int getLastDayOf(int month, int year) {
    switch (month) {
        case Calendar.APRIL:
        case Calendar.JUNE:
        case Calendar.SEPTEMBER:
        case Calendar.NOVEMBER:
            return 30;
        case Calendar.FEBRUARY:
            if (year % 4 == 0) {
                return 29;
            }
            return 28;
        default:
            return 31;
    }
}

因为这些值是普遍存在的!

于 2021-06-12T04:52:44.087 回答
-1

使用GregorianCalendar. 设置对象的日期,然后使用getActualMaximum(Calendar.DAY_IN_MONTH).

http://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html#getActualMaximum%28int%29(但在 Java 1.4 中是一样的)

于 2012-11-29T11:13:29.330 回答
-1
public static String getLastDayOfMonth(int year, int month) throws Exception{
    DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    Date date = sdf.parse(year+"-"+(month<10?("0"+month):month)+"-01");

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);

    calendar.add(Calendar.MONTH, 1);
    calendar.set(Calendar.DAY_OF_MONTH, 1);
    calendar.add(Calendar.DATE, -1);

    Date lastDayOfMonth = calendar.getTime();

    return sdf.format(lastDayOfMonth);
}
public static void main(String[] args) throws Exception{
    System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 1));
    System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 2));
    System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 3));
    System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 4));
    System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 5));
    System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 6));
    System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 7));
    System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 8));
    System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 9));
    System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 10));
    System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 11));
    System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 12));
    System.out.println("Last Day of Month: " + getLastDayOfMonth(2018, 1));
    System.out.println("Last Day of Month: " + getLastDayOfMonth(2018, 2));
    System.out.println("Last Day of Month: " + getLastDayOfMonth(2018, 3));

    System.out.println("Last Day of Month: " + getLastDayOfMonth(2010, 2));
    System.out.println("Last Day of Month: " + getLastDayOfMonth(2011, 2));
    System.out.println("Last Day of Month: " + getLastDayOfMonth(2012, 2));
    System.out.println("Last Day of Month: " + getLastDayOfMonth(2013, 2));
    System.out.println("Last Day of Month: " + getLastDayOfMonth(2014, 2));
    System.out.println("Last Day of Month: " + getLastDayOfMonth(2015, 2));
    System.out.println("Last Day of Month: " + getLastDayOfMonth(2016, 2));
    System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 2));
    System.out.println("Last Day of Month: " + getLastDayOfMonth(2018, 2));
    System.out.println("Last Day of Month: " + getLastDayOfMonth(2019, 2));
    System.out.println("Last Day of Month: " + getLastDayOfMonth(2020, 2));
    System.out.println("Last Day of Month: " + getLastDayOfMonth(2021, 2));
}

输出:

每月最后一天:2017-01-31
每月最后一天:2017-02-28
每月最后一天:2017-03-31
每月最后一天:2017-04-30 每月
最后一天:2017-05-31每月最后一天
:2017-06-30 每月
最后一天:2017-07-31每月最后一天
:2017-08-31 每月
最后一天:2017-09-30 每月
最后一天:2017-10-31每月最后一天
:2017-11-30 每月
最后一天:2017-12-31 每月最后一天:2018-01-31 每月最后一天:2018-02-28 每月
最后
一天:
2018-03-31
每月最后一天:2010-02-28
每月最后一天:2011-02-28
每月最后一天:2012-02-29 每月
最后一天:2013-02-28
每月最后一天:2014-02-28
每月最后一天:2015-02-28
每月最后一天:2016-02-29
每月最后一天:2017-02-28 每月
最后一天:2018-02-28
每月最后一天:2019-02-28 每月最后一天:2020-02-29 每月 最后
一天:2021-02-28

于 2017-10-31T05:57:02.297 回答
-1

您可以使用Java 8中的plusMonthsminusDays方法:

// Parse your date into a LocalDate
LocalDate parsed = LocalDate.parse("1/13/2012", DateTimeFormatter.ofPattern("M/d/yyyy"));

// We only care about its year and month, set the date to first date of that month
LocalDate localDate = LocalDate.of(parsed.getYear(), parsed.getMonth(), 1);

// Add one month, subtract one day 
System.out.println(localDate.plusMonths(1).minusDays(1)); // 2012-01-31
于 2018-11-25T17:48:03.977 回答
-1

最后我发现解决方案已经过测试并且有效

public static Date toDate(String date, String DATE_FORMAT) {
    Date dt = null;
    try {
        String[] d = date.split(" ");
        String[] f = DATE_FORMAT.split(" ");
        if (d.length > 1) {
            if(f.length > 1) {
                DateFormat df = new SimpleDateFormat(DATE_FORMAT);
                df.setLenient(false);
                dt = df.parse(date);
            }
            else
            {
                DateFormat df = new SimpleDateFormat(f[0]);
                df.setLenient(false);
                dt = df.parse(date);
            }
        } else {
            DateFormat df = new SimpleDateFormat(f[0]);
            df.setLenient(false);
            dt = df.parse(date);
        }
        return dt;
    } catch (ParseException e) {

        return null;
    }
}

private SimpleDateFormat dateFormatter;
dateFormatter = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
String StartDate = "05/01/2021";
Calendar endDate = new GregorianCalendar();
Date convertedDate = toDate(StartDate, "MM/dd/yyyy");
endDate.setTime(convertedDate);
endDate.set(Calendar.DAY_OF_MONTH, 1);
endDate.add(Calendar.MONTH, 1);
endDate.add(Calendar.DATE, -1);
String EndDate = dateFormatter.format(endDate.getTime());

出局:2021 年 5 月 31 日

于 2021-10-13T09:42:09.697 回答
-2

对我来说很好用

    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone());
    cal.set(Calendar.MONTH, month-1);  
    cal.set(Calendar.YEAR, year);  
    cal.add(Calendar.DATE, -1);  
    cal.set(Calendar.DAY_OF_MONTH, 
    cal.getActualMaximum(Calendar.DAY_OF_MONTH));
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    return cal.getTimeInMillis();
于 2017-09-29T12:13:15.020 回答
-3

我在我的 JasperServer 报告中使用了这个单行:

new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyy-MM-dd").parse(new java.util.Date().format('yyyy') + "-" + (new Integer (new SimpleDateFormat("MM").format(new Date()))+1) + "-01")-1)

看起来不太好,但对我有用。基本上它是在当月加 1,得到那个月的第一天,然后减去一天。

于 2015-02-27T15:53:47.167 回答