在给定的字符串日期中获取该月的最后一天 [英] Getting last day of the month in a given string date

查看:154
本文介绍了在给定的字符串日期中获取该月的最后一天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My input string date is as below:

String date = "1/13/2012";

我得到的月份如下:

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

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

But how do I get the last calendar day of the month in a given String date?

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

E.g.: for a String "1/13/2012" the output must be "1/31/2012".

推荐答案

Java 8及以上版本。



使用 convertedDate.getMonth()。length(convertedDate.isLeapYear())其中 convertedDate LocalDate 的实例。

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

这篇关于在给定的字符串日期中获取该月的最后一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆