Search code examples
javadatetimeunix-timestampjava-time

Timestamps of start and end of month in java


I want a program in which I give month and year and the program should return start and end timestamp of the month.

For example, if I pass January and 2011 to the method it will return start=1293840000 end = 1296518400

Is there any way to do this.


Solution

  • You can do something like this

    long startDate;
    long endDate;
    
    private void calculateMonthStartAndEndTime(int month, int year){
    //create the first date of month
    Calendar mycal = new GregorianCalendar(year,month, 1);
    startDate = mycal.getTimeInMillis();
    
    // Get the number of days in that month which actually gives the last date.
    int lastDate = mycal.getActualMaximum(Calendar.DAY_OF_MONTH);
    mycal = new GregorianCalendar(year, month, lastDate);
    endDate = mycal.getTimeInMillis();
    }