简体   繁体   English

使用Calendar Java获取本月的最后一天XY

[英]Getting last Day of Month XY with Calendar Java

I need to get the last date of a given month, in my case I need to get the last Date of June. 我需要获取给定月份的最后日期,就我而言,我需要获取六月的最后日期。 My code is following: 我的代码如下:

cal.set(Calendar.DAY_OF_MONTH,
            Calendar.getInstance().getActualMinimum(Calendar.DAY_OF_MONTH));
    int month = cal.get(Calendar.MONTH) + 1;

    if (month <= 6) {
        cal.set(Calendar.DAY_OF_YEAR, Calendar.getInstance()
                .getActualMaximum(Calendar.JUNE));
        return (Calendar) cal;
    } else {
        cal.set(Calendar.DAY_OF_YEAR, Calendar.getInstance()
                .getActualMaximum(Calendar.DAY_OF_YEAR));
        return (Calendar) cal;
    }

At first I get the actual month and wether it's the first half of the year or the second in need another date, always the last date of that half year. 起初,我得到了实际的月份,并且它是该年的上半年或第二个需要另一个日期,总是那个半年的最后一个日期。 With the code above the return is 上面的代码返回的是

2015-01-31

and not 2015-06-31 as I thought it should be. 而不是我认为应该的2015-06-31。 How could I possibly fix this? 我该如何解决?

Your code is all over the place at the moment, unfortunately - you're creating new calendars multiple times for no obvious reason, and you're calling Calendar.getActualMaximum passing in the wrong kind of constant (a value rather than a field). 不幸的是,您的代码此刻无处不在-您无缘无故地多次创建新的日历,并且正在调用Calendar.getActualMaximum传递了错误的常量类型(值而不是字段)。

You want something like: 您想要类似的东西:

int month = cal.get(Calendar.MONTH) <= Calendar.JUNE
    ? Calendar.JUNE : Calendar.DECEMBER;
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calenday.DAY_OF_MONTH));
return cal;

However, I would strongly recommend using java.time if you're on Java 8, and Joda Time if you're not - both are much, much better APIs than java.util.Calendar . 但是,如果您使用的是Java 8,我强烈建议您使用java.time如果您使用的不是Java,我强烈建议您使用java.time这两个API都比java.util.Calendar好得多。

java.time java.time

Much easier now with the modern java.time classes. 现在,使用现代的java.time类要容易得多 Specifically, the YearMonth , Month , and LocalDate classes. 具体来说,是YearMonthMonthLocalDate类。

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone. LocalDate类表示没有日期和时区的仅日期值。

A time zone is crucial in determining a date. 时区对于确定日期至关重要。 For any given moment, the date varies around the globe by zone. 在任何给定时刻,日期都会在全球范围内变化。 For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec . 例如, 法国巴黎午夜过后几分钟是新的一天,而在魁北克蒙特利尔仍然是“昨天”。

If no time zone is specified, the JVM implicitly applies its current default time zone. 如果未指定时区,则JVM隐式应用其当前的默认时区。 That default may change at any moment, so your results may vary. 该默认值可能随时更改,因此您的结果可能会有所不同。 Better to specify your desired/expected time zone explicitly as an argument. 最好将您的期望/期望时区明确指定为参数。

Specify a proper time zone name in the format of continent/region , such as America/Montreal , Africa/Casablanca , or Pacific/Auckland . continent/region的格式指定正确的时区名称 ,例如America/MontrealAfrica/CasablancaPacific/Auckland Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!). 切勿使用ESTIST等3-4个字母的缩写,因为它们不是真实的时区,不是标准化的,甚至不是唯一的(!)。

ZoneId z = ZoneId.of( "America/Montreal" ) ;  
LocalDate today = LocalDate.now( z ) ;

If you want to use the JVM's current default time zone, ask for it and pass as an argument. 如果要使用JVM的当前默认时区,请提出要求并作为参数传递。 If omitted, the JVM's current default is applied implicitly. 如果省略,则隐式应用JVM的当前默认值。 Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM. 最好明确一点,因为缺省值可以在运行时随时由JVM中任何应用程序的任何线程中的任何代码更改。

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.

Or specify a date. 或指定一个日期。 You may set the month by a number, with sane numbering 1-12 for January-December. 您可以用数字设置月份,一月至十二月的理智编号为1-12。

LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ;  // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.

Or, better, use the Month enum objects pre-defined, one for each month of the year. 或者,最好使用预定义的Month枚举对象,一年中的每个月使用一个。 Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety . 提示:在整个代码库中使用这些Month对象,而不是仅使用整数,可以使您的代码更具自文档性,确保有效值并提供类型安全

LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;

YearMonth

With a LocalDate in hand, get the year-month of that date. 有了LocalDate ,即可获取该日期的年月。

YearMonth ym = YearMonth.from( ld ) ;

See which half year it is in. 看看是哪一年。

Set < Month > firstHalfOfYear = EnumSet.range( Month.JANUARY , Month.JUNE ); // Populate the set with first six months of the year.
boolean isFirstHalf = firstHalfOfYear.contains( ym.getMonth() );

Knowing which half of the year, get the end of June or the end of December in the same year. 知道一年中的哪半年,就可以在同一年的六月底或十二月底。

LocalDate result = null;
if ( isFirstHalf ) {
    result = ym.withMonth( Month.JUNE.getValue() ).atEndOfMonth();
} else {  // Else in last half of year.
    result = ym.withMonth( Month.DECEMBER.getValue() ).atEndOfMonth();
}

About java.time 关于java.time

The java.time framework is built into Java 8 and later. java.time框架内置于Java 8及更高版本中。 These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat . 这些类取代了麻烦的旧的旧式日期时间类,例如java.util.DateCalendarSimpleDateFormat

The Joda-Time project, now in maintenance mode , advises migration to the java.time classes. 现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial . 要了解更多信息,请参见Oracle教程 And search Stack Overflow for many examples and explanations. 并在Stack Overflow中搜索许多示例和说明。 Specification is JSR 310 . 规格为JSR 310

You may exchange java.time objects directly with your database. 您可以直接与数据库交换java.time对象。 Use a JDBC driver compliant with JDBC 4.2 or later. 使用与JDBC 4.2或更高版本兼容的JDBC驱动程序 No need for strings, no need for java.sql.* classes. 不需要字符串,不需要java.sql.*类。

Where to obtain the java.time classes? 在哪里获取java.time类?

The ThreeTen-Extra project extends java.time with additional classes. ThreeTen-Extra项目使用其他类扩展了java.time。 This project is a proving ground for possible future additions to java.time. 该项目为将来可能在java.time中添加内容提供了一个试验场。 You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more . 您可以在这里找到一些有用的类,比如IntervalYearWeekYearQuarter ,和更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM