[英]Getting last day of the month in a given string date
我输入的字符串日期如下:
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"
。
通过使用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.util.Calendar
的getActualMaximum
方法:
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));
这看起来像您的需求:
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
通过使用 java 8 java.time.LocalDate
String date = "1/13/2012";
LocalDate lastDayOfMonth = LocalDate.parse(date, DateTimeFormatter.ofPattern("M/dd/yyyy"))
.with(TemporalAdjusters.lastDayOfMonth());
YearMonth // Represent the year and month, without a date and without a time zone.
.from( // Extract the year and month from a `LocalDate` (a year-month-day).
LocalDate // Represent a date without a time-of-day and without a time zone.
.parse( // Get a date from an input string.
"1/13/2012" , // Poor choice of format for a date. Educate the source of your data about the standard ISO 8601 formats to be used when exchanging date-time values as text.
DateTimeFormatter // Specify a formatting pattern by which to parse the input string.
.ofPattern( "M/d/uuuu" ) // Match the pattern of your input.
) // Returns a `LocalDate` object.
) // Returns a `YearMonth` object.
.atEndOfMonth() // Determines the last day of the month for that particular year-month, and returns a `LocalDate` object.
.toString() // Generate text representing the value of that `LocalDate` object using standard ISO 8601 format.
2012-01-31
YearMonth
YearMonth
类使这变得容易。 atEndOfMonth
方法返回一个LocalDate
。 闰年二月被计算在内。
首先定义格式模式以匹配您的字符串输入。
DateTimeFormatter f = DateTimeFormatter.ofPattern( "M/d/uuuu" );
使用该格式化程序从字符串输入中获取LocalDate
。
String s = "1/13/2012" ;
LocalDate ld = LocalDate.parse( "1/13/2012" , f ) ;
然后提取一个YearMonth
对象。
YearMonth ym = YearMonth.from( ld ) ;
要求YearMonth
确定该月的最后一天,即二月的闰年。
LocalDate endOfMonth = ym.atEndOfMonth() ;
以标准 ISO 8601 格式生成表示该日期的文本。
String output = endOfMonth.toString() ;
java.time框架内置于 Java 8 及更高版本中。 这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date
、 Calendar
和SimpleDateFormat
。
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
要了解更多信息,请参阅Oracle 教程。 并在 Stack Overflow 中搜索许多示例和解释。 规范是JSR 310 。
您可以直接与数据库交换java.time对象。 使用符合JDBC 4.2或更高版本的JDBC 驱动程序。 不需要字符串,不需要java.sql.*
类。
在哪里获取 java.time 类?
ThreeTen-Extra项目用附加类扩展了 java.time。 这个项目是未来可能添加到 java.time 的试验场。 您可能会在这里找到一些有用的类,例如Interval
、 YearWeek
、 YearQuarter
等等。
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();
使用 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
如果日期字符串中有时间信息,则应使用
LocalDateTime
而不是LocalDate
。 浏览器2015/07/22 16:49
最简单的方法是构造一个新的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 表示一月。
您可以使用以下代码获取该月的最后一天
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;
}
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 中测试。 我希望这会对某些人有所帮助。
我认为最简单和最快的方法是
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;
}
}
由于这些值普遍不变!
使用GregorianCalendar
。 设置对象的日期,然后使用getActualMaximum(Calendar.DAY_IN_MONTH)
。
http://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html#getActualMaximum%28int%29 (但在 Java 1.4 中是一样的)
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
您可以使用 Java 8 中的plusMonths和minusDays方法:
// 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
最后我发现解决方案已经过测试并且有效
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 日
这个对我来说很好用
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();
我在我的 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,获取该月的第一天并减去一天。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.