Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first date of current month in java

Tags:

java

calendar

People also ask

How to get current month start date in java?

Date currentMonth = new Date(); String yyyyMM = new SimpleDateFormat("yyyyMM"). format(currentMonth); Date firstDateOfMonth = new SimpleDateFormat("yyyyMM"). parse(yyyyMM); ...

How do I find the last day of the month LocalDate?

The atEndOfMonth() method of YearMonth class in Java is used to return a LocalDate of the last day of month based on this YearMonth object with which it is used.


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

tl;dr

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

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

Or…

LocalDate.now().withDayOfMonth( 1 )

Or…

YearMonth.now().atDay( 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(!).

In code, first we determine today’s date as seen in the particular time zone.

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

Then we adjust the day-of-month to the 1st.

LocalDate firstOfCurrentMonth = today.with ( ChronoField.DAY_OF_MONTH , 1 );

Or, more simply:

LocalDate firstOfCurrentMonth = today.withDayOfMonth( 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.


Calendar date = Calendar.getInstance();
date.set(Calendar.DAY_OF_MONTH, 1);

Joda Time

If I am understanding the question correctly, it can be done very easily by using joda time

LocalDate fromDate = new LocalDate().withDayOfMonth(1);
LocalDate toDate = new LocalDate().minusDays(1);

You can use withDayOfMonth(int dayOfMonth) method from java8 to return first day of month:

LocalDate firstDay = LocalDate.now().withDayOfMonth(1);
System.out.println(firstDay);   // 2019-09-01

If you also want the time is set to 0 the code is:

import java.util.*;
import java.text.*;

public class DateCalculations {
  public static void main(String[] args) {

    Calendar aCalendar = Calendar.getInstance();

    aCalendar.set(Calendar.DATE, 1);
    aCalendar.set(Calendar.HOUR_OF_DAY, 0);
    aCalendar.set(Calendar.MINUTE, 0);
    aCalendar.set(Calendar.SECOND, 0);

    Date firstDateOfCurrentMonth = aCalendar.getTime();

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zZ");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

    String dayFirst = sdf.format(firstDateOfCurrentMonth);
    System.out.println(dayFirst);
  }
}

You can check online easily without compiling by using: http://www.browxy.com/