Get first date of current month in java

前端 未结 9 1746
日久生厌
日久生厌 2020-11-29 05:28

I am trying to get to and from date where ToDate will have previous date and FromDate will have first date of the current month. For January it wou

相关标签:
9条回答
  • 2020-11-29 06:27

    try

        Calendar c = Calendar.getInstance();   // this takes current date
        c.set(Calendar.DAY_OF_MONTH, 1);
        System.out.println(c.getTime());       // this returns java.util.Date
    

    Updated (Since Java 8):

    import java.time.LocalDate;
    LocalDate todaydate = LocalDate.now();
    System.out.println("Months first date in yyyy-mm-dd: " +todaydate.withDayOfMonth(1));
    
    0 讨论(0)
  • 2020-11-29 06:29

    tl;dr

    How to get the first date of the current month correctly?

    LocalDate.now()
             .with( TemporalAdjusters.firstDayOfMonth() )
    

    Or…

    YearMonth.now().atDay( 1 )
    

    Or…

    LocalDate.now().with ( ChronoField.DAY_OF_MONTH , 1 )
    

    java.time

    The java.time framework in Java 8 and later supplants the old java.util.Date/.Calendar classes. The old classes have proven to be troublesome, confusing, and flawed. Avoid them.

    The java.time framework is inspired by the highly-successful Joda-Time library, defined by JSR 310, extended by the ThreeTen-Extra project, and explained in the Tutorial.

    LocalDate

    For a date-only value, without time-of-day, use the LocalDate class. While LocalDate has no assigned time zone, we must specify a time zone in order to determine a date such as “today”. For example, a new day dawns earlier in Paris than in Montréal.

    Time zone is crucial in determining today's date. For any given moment, the date varies around the world by zone. Omitting the time zone means the JVM’s current time zone is automatically applied in determining the current date. Any code in the JVM can change the default at runtime, so you are walking on shifting sands. Better to specify your desired/expected time zone explicitly than rely implicitly on the current default.

    Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/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(!).

    ZoneId zoneId = ZoneId.of ( "America/Montreal" );
    LocalDate today = LocalDate.now ( zoneId );
    LocalDate firstOfCurrentMonth = today.with ( ChronoField.DAY_OF_MONTH , 1 );
    

    Dump to console.

    System.out.println ( "For zoneId: " + zoneId + " today is: " + today + " and first of this month is " + firstOfCurrentMonth );
    

    For zoneId: America/Montreal today is: 2015-11-08 and first of this month is 2015-11-01

    Alternatively, use a TemporalAdjuster. For your purpose, you will find handy implementations in the TemporalAdjusters class (note plural s), specifically firstDayOfMonth.

    LocalDate firstOfCurrentMonth = today.with( TemporalAdjusters.firstDayOfMonth() ) ;
    

    ZonedDateTime

    If you need a time of day, remember that 00:00:00.000 is not always the first moment of the day because of Daylight Saving Time (DST) and perhaps other anomalies. So let java.time determine the correct time of the first moment of the day.

    ZonedDateTime zdt = firstOfCurrentMonth.atStartOfDay ( zoneId );
    

    2015-11-01T00:00-04:00[America/Montreal]


    About java.time

    The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

    The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

    To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

    Where to obtain the java.time classes?

    • Java SE 8, Java SE 9, and later
      • Built-in.
      • Part of the standard Java API with a bundled implementation.
      • Java 9 adds some minor features and fixes.
    • Java SE 6 and Java SE 7
      • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • Android
      • Later versions of Android bundle implementations of the java.time classes.
      • For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

    The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

    0 讨论(0)
  • 2020-11-29 06:29

    In order to get a Date (that can be used in JPA later on), I did

    Date startOfMonth = Date.from(LocalDate.now().withDayOfMonth(1).atStartOfDay().toInstant(ZoneOffset.UTC));
    
    • I take current date LocalDate.now()
    • Move it to first day of the month withDayOfMonth(1)
    • Move it to the sart of the day atStartOfDay() to get rid of hours and minutes
    • and deal with the TimeZone issues by changing it into an Instant with the "right" ZoneOffset.
    0 讨论(0)
提交回复
热议问题