简体   繁体   中英

Get first date of current month in java

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 would be 1/1/2013 and so on. How to get the first date of the current month correctly? I am not able to do it.

today.add(Calendar.DAY_OF_MONTH, -1);
java.util.Date previousDay=today.getTime();
ToDate = sdfFile1.format(newjava.sql.Date(previousDay.getTime()));
today.add(Calendar.DATE, 1);
java.util.Date nextDay=today.getTime();
FromDate = sdfFile1.format(new java.sql.Date(nextDay.getTime()));

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?

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/

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.

Works Like a charm!

public static String  getCurrentMonthFirstDate(){
    Calendar c = Calendar.getInstance();   
    c.set(Calendar.DAY_OF_MONTH, 1);
    DateFormat df = new SimpleDateFormat("MM-dd-yyyy");
    //System.out.println(df.format(c.getTime())); 
    return df.format(c.getTime());
}

//Correction :output =02-01-2018 在此处输入图像描述

import java.util.Date;
import java.text.SimpleDateFormat;

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

my stupid solution. but it's work for me :D

In Java 8 you can use:

LocalDate date = LocalDate.now(); //2020-01-12
date.withDayOfMonth(1); //2020-01-01

First day of month of a date:

public static Date firstDayOfMonth(Date d) {
    
    Calendar calendar = new GregorianCalendar();
    calendar.setTime(d);
    calendar.set(Calendar.DAY_OF_MONTH, 1);
    
    return calendar.getTime();  
}

Another way by using JodaTime package depends on ur requirement can use Zone it or you can remove

import org.joda.time.DateTimeZone;
DateTime previousMonthStartDate = DateTime.now().minusMonths(1).withDayOfMonth(1).toDateTime(DateTimeZone.forID("Asia/Calcutta"));
    String previousMonthStDate = previousMonthStartDate.toString("yyyy-MMMM-dd");
    System.out.println(previousMonthStDate);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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