获取给定字符串日期中该月的最后一天

2022-08-31 13:13:58

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

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"


答案 1

Java 8 及更高版本。

通过使用 where 是 的实例。convertedDate.getMonth().length(convertedDate.isLeapYear())convertedDateLocalDate

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 及更低版本。

通过使用以下方法:getActualMaximumjava.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));

答案 2

这看起来像您的需求:

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