我的输入字符串日期如下:
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"
。
答案 0 :(得分:135)
使用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()));
使用getActualMaximum
的{{1}}方法:
java.util.Calendar
答案 1 :(得分:23)
这看起来像你的需要:
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
答案 2 :(得分:6)
使用java 8 java.time.LocalDate
String date = "1/13/2012";
LocalDate lastDayOfMonth = LocalDate.parse(date,DateTimeFormatter.ofPattern("M/dd/yyyy"));
.with(TemporalAdjusters.lastDayOfMonth());
答案 3 :(得分:5)
使用Java 8
public static String guessEncoding(byte[] bytes) { String DEFAULT_ENCODING = "UTF-8"; org.mozilla.universalchardet.UniversalDetector detector = new org.mozilla.universalchardet.UniversalDetector(null); detector.handleData(bytes, 0, bytes.length); detector.dataEnd(); String encoding = detector.getDetectedCharset(); System.out.println("Detected encoding: " + encoding); detector.reset(); if (encoding == null) { encoding = DEFAULT_ENCODING; } return encoding; }
/DateTime
:
LocalDateTime
OR
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
。 I.E.LocalDate
答案 4 :(得分:2)
最简单的方法是构建一个新的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日历字段的值。月值基于0,例如一月份为0。
答案 5 :(得分:2)
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.ofPattern( "M/d/uuuu" ) // Specify a formatting pattern by which to parse the input string.
) // 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.
请参阅此code run live at IdeOne.com。
2012-01-31
YearMonth
YearMonth
类使此操作变得容易。 atEndOfMonth
方法返回一个LocalDate
。 February年二月占。
首先定义一种格式设置模式以匹配您的字符串输入。
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
以确定当年该月的最后一天,占2月份的Leap Year。
LocalDate endOfMonth = ym.atEndOfMonth() ;
以标准ISO 8601格式生成表示该日期的文本。
String output = endOfMonth.toString() ;
java.time框架已内置在Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如java.util.Date
,Calendar
和SimpleDateFormat
。
目前位于Joda-Time的maintenance mode项目建议迁移到java.time类。
要了解更多信息,请参见Oracle Tutorial。并在Stack Overflow中搜索许多示例和说明。规格为JSR 310。
您可以直接与数据库交换 java.time 对象。使用符合JDBC driver或更高版本的JDBC 4.2。不需要字符串,不需要java.sql.*
类。
在哪里获取java.time类?
ThreeTen-Extra项目使用其他类扩展了java.time。该项目为将来可能在java.time中添加内容提供了一个试验场。您可能会在这里找到一些有用的类,例如Interval
,YearWeek
,YearQuarter
和more。
答案 6 :(得分:1)
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();
答案 7 :(得分:1)
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中测试。 我希望这会有所帮助。
答案 8 :(得分: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;
}
答案 9 :(得分:0)
我认为最简单快捷的方法是
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;
}
}
因为这些值普遍不变!
答案 10 :(得分:-1)
使用GregorianCalendar
。设置对象的日期,然后使用getActualMaximum(Calendar.DAY_IN_MONTH)
。
http://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html#getActualMaximum%28int%29(但在Java 1.4中也是如此)
答案 11 :(得分:-1)
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
答案 12 :(得分:-1)
您可以在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
答案 13 :(得分:-2)
用这个
为我工作 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();
答案 14 :(得分:-3)
我在JasperServer Reports上使用了这个单行程序:
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,得到该月的第一天并减去一天。