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

新手上路,请多包涵

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

 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"

原文由 Vicky 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 594
2 个回答

Java 8 及更高版本。

通过使用 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 及以下版本。

通过使用 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));

原文由 Aleksandr M 发布,翻译遵循 CC BY-SA 3.0 许可协议

这看起来像您的需求:

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

原文由 SG 86 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题