Start and end date of a current month
Asked Answered
A

14

48

I need the start date and the end date of the current month in Java. When the JSP page is loaded with the current month it should automatically calculate the start and end date of that month. It should be irrespective of the year and month. That is some month has 31 days or 30 days or 28 days. This should satisfy for a leap year too. Can you help me out with that?

For example if I select month May in a list box I need starting date that is 1 and end date that is 31.

Ammeter answered 21/6, 2010 at 10:17 Comment(0)
A
73

There you go:

public Pair<Date, Date> getDateRange() {
    Date begining, end;

    {
        Calendar calendar = getCalendarForNow();
        calendar.set(Calendar.DAY_OF_MONTH,
                calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
        setTimeToBeginningOfDay(calendar);
        begining = calendar.getTime();
    }

    {
        Calendar calendar = getCalendarForNow();
        calendar.set(Calendar.DAY_OF_MONTH,
                calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        setTimeToEndofDay(calendar);
        end = calendar.getTime();
    }

    return Pair.of(begining, end);
}

private static Calendar getCalendarForNow() {
    Calendar calendar = GregorianCalendar.getInstance();
    calendar.setTime(new Date());
    return calendar;
}

private static void setTimeToBeginningOfDay(Calendar calendar) {
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
}

private static void setTimeToEndofDay(Calendar calendar) {
    calendar.set(Calendar.HOUR_OF_DAY, 23);
    calendar.set(Calendar.MINUTE, 59);
    calendar.set(Calendar.SECOND, 59);
    calendar.set(Calendar.MILLISECOND, 999);
}

PS: Pair class is simply a pair of two values.

Absalom answered 21/6, 2010 at 10:23 Comment(2)
This is good, but Pair is a terrible abstraction for a date range. Creating a real entity called DateRange would be much better as it would give you a place to add logic.Nevertheless
I agree. I wrote this just as an example.Absalom
P
35

If you have the option, you'd better avoid the horrid Java Date API, and use instead Jodatime (or equivalently the Java 8 java.time.* API). Here is an example:

LocalDate monthBegin = new LocalDate().withDayOfMonth(1);
LocalDate monthEnd = new LocalDate().plusMonths(1).withDayOfMonth(1).minusDays(1);
Piquant answered 21/6, 2010 at 11:39 Comment(3)
Now, with java 8 you can do this with java time: docs.oracle.com/javase/8/docs/api/java/time/…Soelch
You can try this: LocalDate monthBegin = LocalDate.now().withDayOfMonth(1); LocalDate monthEnd = LocalDate.now().plusMonths(1).withDayOfMonth(1).minusDays(1);Crescent
Replace new LocalDate() with LocalDate.now()Standice
G
18

Try LocalDate from Java 8:

LocalDate today = LocalDate.now();
System.out.println("First day: " + today.withDayOfMonth(1));
System.out.println("Last day: " + today.withDayOfMonth(today.lengthOfMonth()));
Gold answered 27/10, 2016 at 4:42 Comment(0)
B
9

Simple and Best, Try this One

Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MONTH, 0);
            calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
            Date monthFirstDay = calendar.getTime();
            calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
            Date monthLastDay = calendar.getTime();

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String startDateStr = df.format(monthFirstDay);
        String endDateStr = df.format(monthLastDay);

        Log.e("DateFirstLast",startDateStr+" "+endDateStr);
Buffo answered 21/9, 2019 at 6:52 Comment(1)
I beg to differ. It’s best to avoid the classes Calendar, Date and SimpleDateFormat. They are poorly designed and long outdated. Instead use java.time, the modern Java date and time API. See for example the much better and also simpler answer by aianitro.Thun
E
5
Calendar c = Calendar.getInstance();
    int year = c.get(Calendar.YEAR);
    int month = c.get(Calendar.MONTH);
    int day = 1;
    c.set(year, month, day);
    int numOfDaysInMonth = c.getActualMaximum(Calendar.DAY_OF_MONTH);
    System.out.println("First Day of month: " + c.getTime());
    c.add(Calendar.DAY_OF_MONTH, numOfDaysInMonth-1);
    System.out.println("Last Day of month: " + c.getTime());
Elwira answered 21/1, 2016 at 7:3 Comment(1)
As there are multiple other answers and even an accepted one, you should provide a bit of reasoning, what distinguishes your answer from the others.Acquaint
L
4

With the date4j library :

dt.getStartOfMonth();
dt.getEndOfMonth();
Lenoir answered 13/2, 2011 at 2:56 Comment(0)
U
3

Try this Code

Calendar calendar = Calendar.getInstance();
int yearpart = 2010;
int monthPart = 11;
int dateDay = 1;
calendar.set(yearpart, monthPart, dateDay);
int numOfDaysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println("Number of Days: " + numOfDaysInMonth);
System.out.println("First Day of month: " + calendar.getTime());
calendar.add(Calendar.DAY_OF_MONTH, numOfDaysInMonth-1);
System.out.println("Last Day of month: " + calendar.getTime());

Hope it helps.

Unnumbered answered 4/9, 2015 at 13:30 Comment(0)
I
3

if you have java.time.YearMonth you can do:

YearMonth startYearMonth = YearMonth.now();
java.time.LocalDate startOfMonthDate = startYearMonth.atDay(1);    
java.time.LocalDate endOfMonthDate   = startYearMonth.atEndOfMonth();
Irrelative answered 29/8, 2021 at 20:52 Comment(0)
E
1
Date begining, ending;
Calendar calendar_start =BusinessUnitUtility.getCalendarForNow();
  calendar_start.set(Calendar.DAY_OF_MONTH,calendar_start.getActualMinimum(Calendar.DAY_OF_MONTH));
  begining = calendar_start.getTime();
  String start= DateDifference.dateToString(begining,"dd-MMM-yyyy");//sdf.format(begining);


   //            for End Date of month
  Calendar calendar_end = BusinessUnitUtility.getCalendarForNow();
  calendar_end.set(Calendar.DAY_OF_MONTH,calendar_end.getActualMaximum(Calendar.DAY_OF_MONTH));
      ending = calendar_end.getTime();
      String end=DateDifference.dateToString(ending,"dd-MMM-yyyy");//or sdf.format(end);

enter code here



public static Calendar getCalendarForNow() {
        Calendar calendar = GregorianCalendar.getInstance();
        calendar.setTime(new Date());
        return calendar;
    }
Eelpout answered 6/4, 2011 at 10:0 Comment(1)
this code will be help to getting Start Date and Ending date of the Current monthEelpout
G
0

For Java 8+, below method will given current month first & last dates as LocalDate instances.

public static LocalDate getCurrentMonthFirstDate() {
    return LocalDate.ofEpochDay(System.currentTimeMillis() / (24 * 60 * 60 * 1000) ).withDayOfMonth(1);
}

public static LocalDate getCurrentMonthLastDate() {
    return LocalDate.ofEpochDay(System.currentTimeMillis() / (24 * 60 * 60 * 1000) ).plusMonths(1).withDayOfMonth(1).minusDays(1);
}

Side note: Using LocalDate.ofEpochDay(...) instead of LocalDate.now() gives much improved performance. Also, using the millis-in-a-day expression instead of the end value, which is 86400000 is performing better. I initially thought the latter would perform better than the the expression :P

Gyrate answered 29/4, 2015 at 18:16 Comment(0)
P
0
public static void main(String[] args) 
    {
        LocalDate today = LocalDate.now();
        System.out.println("First day: " + 
today.withDayOfMonth(1));
        System.out.println("Last day: " + today.withDayOfMonth(today.lengthOfMonth()))
    }
Prospectus answered 7/6, 2019 at 11:11 Comment(2)
Can you please add text to your code answer to enable everybody else to follow you? Thank you!Victorie
@Victorie I give you a write answer for this code , please execute this code on your text editor and run your answer is Fast Day: 2019-6-01 Second Day: 2019-06-30 Thank you young coder, Hope you understandProspectus
S
0

You can implement it as below:

public void FirstAndLastDate() {

    SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");
    //start date of month
    calendarStart = Calendar.getInstance();
    calendarStart.set(Integer.parseInt((new SimpleDateFormat("yyyy")).format(new Date().getTime()))
            , Integer.parseInt((new SimpleDateFormat("MM")).format(new Date().getTime()))
            , Calendar.getInstance().getActualMinimum(Calendar.DAY_OF_MONTH));

    //End Date of month
    calendarEnd = Calendar.getInstance();
    calendarEnd.set(Integer.parseInt((new SimpleDateFormat("yyyy")).format(new Date().getTime()))
            , Integer.parseInt((new SimpleDateFormat("MM")).format(new Date().getTime()))
            , Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH));

    Toast.makeText(this, sdf.format(calendarStart.getTime()) + "\n" + sdf.format(calendarEnd.getTime()), Toast.LENGTH_SHORT).show();

}
Supramolecular answered 10/11, 2019 at 16:10 Comment(1)
Thanks for wanting to contribute. Please don’t teach the young ones to use the long outdated and notoriously troublesome SimpleDateFormat class. At least not as the first option. And not without any reservation. Today we have so much better in java.time, the modern Java date and time API, and its DateTimeFormatter. And a tip: Code only answers are seldom really helpful. It’s from the explanations that we all learn in my experience.Thun
Z
0

A very simple step to get the first day and last day of the month:

    Calendar calendar = Calendar.getInstance();
    
    // Get the current date
    Date today = calendar.getTime();
    
    
    // Setting the first day of month
    calendar.set(Calendar.DAY_OF_MONTH, 1);
    Date firstDayOfMonth = calendar.getTime();

    // Move to next month  
    calendar.add(Calendar.MONTH, 1);
    // setting the 1st day of the month
    calendar.set(Calendar.DAY_OF_MONTH, 1);
    // Move a day back from the date
    calendar.add(Calendar.DATE, -1);
    Date lastDayOfMonth = calendar.getTime();

    // Formatting the date  
    DateFormat sdf = new SimpleDateFormat("dd-MMM-YY");

    String todayStr = sdf.format(today);
    String firstDayOfMonthStr = sdf.format(firstDayOfMonth);
    String lastDayOfMonthStr = sdf.format(lastDayOfMonth);
    
    System.out.println("Today            : " + todayStr);
    System.out.println("Fist Day of Month: "+firstDayOfMonthStr);
    System.out.println("Last Day of Month: "+lastDayOfMonthStr);
Zetana answered 26/8, 2021 at 9:33 Comment(0)
T
-1

Making it more modular, you can have one main function that calculates startDate or EndDate and than you can have individual methods to getMonthStartDate, getMonthEndDate and to getMonthStartEndDate. Use methods as per your requirement.

public static String getMonthStartEndDate(){
    String start = getMonthDate("START");
    String end = getMonthDate("END");
    String result = start + " to " + end;
    return result;
}

public static String getMonthStartDate(){
    String start = getMonthDate("START");
    return start;
}

public static String getMonthEndDate(){
    String end = getMonthDate("END");
    return end;
}

/**
 * @param filter 
 * START for start date of month e.g.  Nov 01, 2013
 * END for end date of month e.g.  Nov 30, 2013
 * @return
 */
public static String getMonthDate(String filter){
            String MMM_DD_COMMA_YYYY       = "MMM dd, yyyy";
    SimpleDateFormat sdf = new SimpleDateFormat(MMM_DD_COMMA_YYYY);
    sdf.setTimeZone(TimeZone.getTimeZone("PST"));
    sdf.format(GregorianCalendar.getInstance().getTime());

    Calendar cal =  GregorianCalendar.getInstance();
    int date = cal.getActualMinimum(Calendar.DATE);
    if("END".equalsIgnoreCase(filter)){
        date = cal.getActualMaximum(Calendar.DATE);
    }
    cal.set(Calendar.DATE, date);
    String result =  sdf.format(cal.getTime());
    System.out.println(" " + result  );

    return result;
}
Tessitura answered 17/11, 2013 at 7:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.