[英]Get Last day of the Month specified in String
I have found some answers based on Calendar to get the last date of the month. 我已经找到一些基于日历的答案,以获取该月的最后日期。
I need a function that takes a string as date 2014-04-01 (yyyy-MM-dd)
format and returns the last date in the same format. 我需要一个将字符串作为日期
2014-04-01 (yyyy-MM-dd)
格式并以相同格式返回最后日期的函数。
if user enters 2014-04-05
I need the function that returns 2014-04-30
. 如果用户输入
2014-04-05
我需要返回2014-04-30
的函数。
The code I am trying is here which takes the current date time but I am stuck with using the getactualmaxium
point and how to use it. 我正在尝试的代码在这里需要当前的日期时间,但是我
getactualmaxium
坚持使用getactualmaxium
点以及如何使用它。
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH,0);
cal.set(Calendar.DATE, 0);
Date firstDateOfPreviousMonth = cal.getTime();
System.out.println(firstDateOfPreviousMonth );
cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));
Date lastDateOfPreviousMonth = cal.getTime();
System.out.println(lastDateOfPreviousMonth );
Check if the following code helps 检查以下代码是否有帮助
public static void main(String[] args) throws ParseException {
String dateStr="2014-04-05";
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
cal.setTime(sdf.parse(dateStr));
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
System.out.println(sdf.format(cal.getTime()));
}
I wouldn't use Calendar if you can use JodaTime or the new JSR-310 DateTime in Java 8. 如果您可以在Java 8中使用JodaTime或新的JSR-310 DateTime,则不会使用Calendar。
String dateStr = "2014-04-05";
LocalDate endOfMonth = LocalDate.parse(dateStr)
.withDayOfMonth(1).plusMonths(1).minusDays(1);
System.out.println(endOfMonth);
What you can do, is take the start of the month, add a month and subtract a day. 您可以做的是从月初开始,加上一个月,然后减去一天。
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.set(Calendar.DATE, 1);
cal.add(Calendar.MONTH, 1);
cal.add(Calendar.DATE, -1);
System.out.println(cal.getTime());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.