How to get start and end date of a year?

前端 未结 15 1793
清酒与你
清酒与你 2021-02-05 02:57

I have to use the Java Date class for this problem (it interfaces with something out of my control).

How do I get the start and end date of a year and then

15条回答
  •  梦谈多话
    2021-02-05 03:24

    Update: The Joda-Time library is now in maintenance mode with its team advising migration to the java.time classes. See the correct java.time Answer by Przemek.

    Time Zone

    The other Answers ignore the crucial issue of time zone.

    Joda-Time

    Avoid doing date-time work with the notoriously troublesome java.util.Date class. Instead use either Joda-Time or java.time. Convert to j.u.Date objects as needed for interoperability.

    DateTimeZone zone = DateTimeZone.forID( "America/Montreal" ) ;
    int year = 2015 ;
    DateTime firstOfYear = new DateTime( year , DateTimeConstants.JANUARY , 1 , 0 , 0 , zone ) ;
    DateTime firstOfNextYear = firstOfYear.plusYears( 1 ) ;
    DateTime firstMomentOfLastDayOfYear = firstOfNextYear.minusDays( 1 ) ;
    

    Convert To java.util.Date

    Convert to j.u.Date as needed.

    java.util.Date d = firstOfYear.toDate() ;
    

提交回复
热议问题