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

Vic*_*cky 59 java calendar date

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

String date = "1/13/2012";
Run Code Online (Sandbox Code Playgroud)

我得到的月份如下:

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

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

例如:对于String "1/13/2012",输出必须是"1/31/2012".

Ale*_*r M 148

Java 8及以上版本.

通过使用convertedDate.getMonth().length(convertedDate.isLeapYear())where 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()));
Run Code Online (Sandbox Code Playgroud)

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));
Run Code Online (Sandbox Code Playgroud)

  • 使用 /sf/answers/2848255581/ 中建议的 `TemporalAdjusters.lastDayOfMonth()` 的 Java 8 解决方案更简单。 (2认同)

SG *_* 86 25

这看起来像您的需求:

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

} 
Run Code Online (Sandbox Code Playgroud)

输出:

Today            : 2010-08-03  
Last Day of Month: 2010-08-31  
Run Code Online (Sandbox Code Playgroud)

  • 仅供参考,非常麻烦的旧日期时间类,例如 [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html),[ `java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html) 和 `java.text.SimpleDateFormat` 现在是[旧版]( https://en.wikipedia.org/wiki/Legacy_system),由 [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package- Summary.html) Java 8 及更高版本中内置的类。请参阅 Oracle 的 [*教程*](https://docs.oracle.com/javase/tutorial/datetime/TOC.html)。 (2认同)

Gau*_*hna 7

通过使用Java 8 java.time.LocalDate

String date = "1/13/2012";
LocalDate lastDayOfMonth = LocalDate.parse(date,DateTimeFormatter.ofPattern("M/dd/yyyy"));
                               .with(TemporalAdjusters.lastDayOfMonth());
Run Code Online (Sandbox Code Playgroud)

  • 我现在明白了。添加一些讨论或解释来做出更好的答案怎么样?例如,提及“TemporalAdjuster”接口和“TemporalAdjusters”实现类。Stack Overflow 不仅仅是一个代码片段库。并且,感谢您的贡献。 (2认同)

Bas*_*que 7

tl;博士

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.
Run Code Online (Sandbox Code Playgroud)

查看此代码在 IdeOne.com 上实时运行

2012-01-31

YearMonth

YearMonth门课让这一切变得容易。该atEndOfMonth方法返回一个LocalDate. 闰年二月是占。

首先定义一个格式化模式以匹配您的字符串输入。

DateTimeFormatter f = DateTimeFormatter.ofPattern( "M/d/uuuu") ;

使用该格式化程序LocalDate从字符串输入中获取 a 。

String s = "1/13/2012" ;
LocalDate ld = LocalDate.parse( "1/13/2012" , f ) ;
Run Code Online (Sandbox Code Playgroud)

然后提取一个YearMonth对象。

YearMonth ym = YearMonth.from( ld ) ;
Run Code Online (Sandbox Code Playgroud)

要求YearMonth确定该年月份的最后一天,考虑2 月份的闰年

LocalDate endOfMonth = ym.atEndOfMonth() ;
Run Code Online (Sandbox Code Playgroud)

以标准 ISO 8601 格式生成表示该日期的文本。

String output = endOfMonth.toString() ;  
Run Code Online (Sandbox Code Playgroud)

关于java.time

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-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多


Zee*_*han 5

使用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); 
Run Code Online (Sandbox Code Playgroud)

要么

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);
Run Code Online (Sandbox Code Playgroud)

输出:

2012-01-31
Run Code Online (Sandbox Code Playgroud)

LocalDateTime应该使用,而不是LocalDate在日期字符串中有时间信息.IE2015/07/22 16:49

  • 确实非常有用,或者也可以使用以下代码查找当月的最大日期.`LocalDate.now().得到月().最大长度()` (2认同)

小智 5

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());
}
Run Code Online (Sandbox Code Playgroud)

以 Basil Bourque 的评论为准

import java.time.YearMonth;

int lastDayOfMonth = YearMonth.of(Y, M).lengthOfMonth();
Run Code Online (Sandbox Code Playgroud)