Calendar - Get last day of previous month - java

I want to get the last day of the previous month.
But this doesnt seem to work:
Calendar cal = Calendar.getInstance();
Integer lastDay = cal.getInstance().getActualMaximum(cal.DAY_OF_MONTH);
cal.add(Calendar.MONTH, -1);
Integer prevMonth = cal.get(Calendar.MONTH);
Integer prevMonthYear = cal.get(Calendar.YEAR);
Integer lastDayPrevMonth = cal.getInstance().getActualMaximum(cal.DAY_OF_MONTH);
System.out.println("Previous month was: " + prevMonth + "-" + prevMonthYear);
System.out.println("Last day in previous month was: " + lastDayPrevMonth);
System.out.println("Last day in this month is: " + lastDay);
This outputs:
I/System.out﹕: Previous month was 10-2015
I/System.out﹕: Last day in previous month was 31
I/System.out﹕: Last day in this month is 31
So it's getting the previous month, that's november (10), giving that it is now december (11).
Last day in this month is also correct, but clearly, last day in previous month was not 31, but 30.
Why does the second getActualMaximum give the same "last-day-in-month" as the first, when I do the add -1 thing?

The problem in your current code is that you are calling multiple times the Calendar.getInstance() method, which returns the current date.
To obtain a Calendar which is the last day of the previous month, you can have the following:
public static void main(String... args) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
System.out.println(cal.get(Calendar.MONTH));
System.out.println(cal.get(Calendar.DAY_OF_MONTH));
}
It subtracts one month from the current month and sets the day of month to its maximum value, obtained with getActualMaximum. Note that the month is 0-based in Calendar so January is actually 0.

You can use LocalDate as below:
LocalDate.now().withDayOfMonth(1).minusDays(1)

Try this, I think it will solve your problem:
/**
* Returns previous month date in string format
* #param date
* #return
*/
private static String getPreviousMonthDate(Date date){
final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.add(Calendar.DATE, -1);
Date preMonthDate = cal.getTime();
return format.format(preMonthDate);
}
/**
* Returns previous to previous month date in string format
* #param date
* #return
*/
private static String getPreToPreMonthDate(Date date){
final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DAY_OF_MONTH,1);
cal.add(Calendar.DATE, -1);
Date preToPreMonthDate = cal.getTime();
return format.format(preToPreMonthDate);
}

Related

how to get next month date from specified date in Android

I'm designing a program where in my recylerview i wanted to display a list of items whose date is 4 days less or more than current date.
This will work for month:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
This will work for -4 day:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, -4);

Formatting java.sql.Date to yyyyMMdd

I am using the below code
#SuppressWarnings("deprecation")
Date d = new Date (2014,01,9);
System.out.println(d);
DateFormat df = new SimpleDateFormat("yyyyMMdd");
final String text = df.format(d);
System.out.println(text);
I am getting below output.
3914-02-09
39140209
Does any one know why there is 3914?
Thanks,
Mahesh
The javadoc for the constructor you're using java.sql.Date(int,int,int) reads (in part),
year - the year minus 1900; must be 0 to 8099. (Note that 8099 is 9999 minus 1900.)
so you should use (assuming you mean this year)
Date d = new Date (2015-1900,01,9);
From Java Docs,
Deprecated. As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date).
Allocates a Date object and initializes it so that it represents midnight, local time, at the beginning of the day specified by the year, month, and date arguments.
Parameters:
year the year minus 1900.
month the month between 0-11.
date the day of the month between 1-31.
Code
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
int year = 2014;
int month = 01;
int day = 9;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month - 1);
cal.set(Calendar.DAY_OF_MONTH, day);
java.sql.Date date = new java.sql.Date(cal.getTimeInMillis());
System.out.println(sdf.format(date));
}
output
2014-01-09

Getting the start and the end date of a week using java calendar class

I want to get the last and the first week of a week for a given date.
e.g if the date is 12th October 2011 then I need the dates 10th October 2011 (as the starting date of the week) and 16th october 2011 (as the end date of the week)
Does anyone know how to get these 2 dates using the calender class (java.util.Calendar)
thanks a lot!
Some code how to do it with the Calendar object. I should also mention joda time library as it can help you many of Date/Calendar problems.
Code
public static void main(String[] args) {
// set the date
Calendar cal = Calendar.getInstance();
cal.set(2011, 10 - 1, 12);
// "calculate" the start date of the week
Calendar first = (Calendar) cal.clone();
first.add(Calendar.DAY_OF_WEEK,
first.getFirstDayOfWeek() - first.get(Calendar.DAY_OF_WEEK));
// and add six days to the end date
Calendar last = (Calendar) first.clone();
last.add(Calendar.DAY_OF_YEAR, 6);
// print the result
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(df.format(first.getTime()) + " -> " +
df.format(last.getTime()));
}
This solution works for any locale (first day of week could be Sunday or Monday).
Date date = new Date();
Calendar c = Calendar.getInstance();
c.setTime(date);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK) - c.getFirstDayOfWeek();
c.add(Calendar.DAY_OF_MONTH, -dayOfWeek);
Date weekStart = c.getTime();
// we do not need the same day a week after, that's why use 6, not 7
c.add(Calendar.DAY_OF_MONTH, 6);
Date weekEnd = c.getTime();
For example, today is Jan, 29 2014. For the locale with Sunday as a first day of week you will get:
start: 2014-01-26
end: 2014-02-01
For the locale with Monday as a first day the dates will be:
start: 2014-01-27
end: 2014-02-02
If you want all dates then
first.add(Calendar.DAY_OF_WEEK,first.getFirstDayOfWeek() - first.get(Calendar.DAY_OF_WEEK));
for (int i = 1; i <= 7; i++) {
System.out.println( i+" Day Of that Week is",""+first.getTime());
first.add(Calendar.DAY_OF_WEEK,1);
}
Here is the sample code
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.set(2016, 2, 15);
{
Calendar startCal = Calendar.getInstance();
startCal.setTimeInMillis(cal.getTimeInMillis());
int dayOfWeek = startCal.get(Calendar.DAY_OF_WEEK);
startCal.set(Calendar.DAY_OF_MONTH,
(startCal.get(Calendar.DAY_OF_MONTH) - dayOfWeek) + 1);
System.out.println("end date : " + startCal.getTime());
}
{
Calendar endCal = Calendar.getInstance();
endCal.setTimeInMillis(cal.getTimeInMillis());
int dayOfWeek = endCal.get(Calendar.DAY_OF_WEEK);
endCal.set(Calendar.DAY_OF_MONTH, endCal.get(Calendar.DAY_OF_MONTH)
+ (7 - dayOfWeek));
System.out.println("start date : " + endCal.getTime());
}
}
which will print
start date : Sun Mar 13 20:30:30 IST 2016
end date : Sat Mar 19 20:30:30 IST 2016
I have found the formula in the accepted answer will only work in some cases. For example your week starts on Saturday and today is Sunday. To arrive at the first day of the week we walk back 1 day, but the formula cal.get(Calendar.DAY_OF_WEEK) - cal.getFirstDayOfWeek() will give the answer -6. The solution is to use a modulus so the formula wraps around so to speak.
int daysToMoveToStartOfWeek = (
7 +
cal.get(Calendar.DAY_OF_WEEK) -
cal.getFirstDayOfWeek()
)%7;
cal.add(Calendar.DAY_OF_WEEK, -1 * daysToMoveToStartOfWeek);

how to get minimum and maximum date from given month in java

how to get minimum and maximum date from given month in java using java.util.Calendar.
The minimum is always the 1st of this month. The maximum can be determined by adding 1 to month and subtracting 1 from the Calendar day field.
This could be done this way:
c = ... // get calendar for month you're interested in
int numberOfDays = c.getActualMaximum(Calendar.DAY_OF_MONTH)
You could find minimum and maximum value the same way for any of components of the date.
Have you tried the following?
After setting your calendar object to your desired month,
calendar.getActualMaximum(Calendar.DATE);
For the minimum, I suppose it's always the first.
Hope that helps.
Minimum date is always 1
and Maximum date can be calculate as
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
int year = 2010;
int month = Calendar.FEBRUARY;
int date = 1;
int maxDay =0;
calendar.set(year, month, date);
System.out.println("First Day: " + formatter.format(calendar.getTime()));
//Getting Maximum day for Given Month
maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
calendar.set(year, month, maxDay);
System.out.println("Last Day: " + formatter.format(calendar.getTime()));
Hopefully this will helps
I got solution as below,
public void ddl_month_valueChange(ValueChangeEvent event) {
int v_month = Integer.parseInt(event.getNewValue().toString()) - 1;
java.util.Calendar c1 = java.util.Calendar.getInstance();
c1.set(2011, v_month, 1);
Date d_set_att_from = c1.getTime();
cal_att_from_date.setValue(d_set_att_from);
c1.add(java.util.Calendar.MONTH, 1);
c1.add(java.util.Calendar.DATE, -1);
Date d_set_att_to = c1.getTime();
cal_att_to_date.setValue(d_set_att_to); }

Java - How to calculate the first and last day of each week

I'm trying to create a weekly calendar that looks like this: http://dhtmlx.com/docs/products/dhtmlxScheduler/sample_basic.html
How can I calculate every week date? For example, this week is:
Monday - Sunday
7 June, 8 June, 9 June, 10 June, 11 June, 12 June, 13 June
I guess this does what you want:
// Get calendar set to current date and time
Calendar c = Calendar.getInstance();
// Set the calendar to monday of the current week
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
// Print dates of the current week starting on Monday
DateFormat df = new SimpleDateFormat("EEE dd/MM/yyyy");
for (int i = 0; i < 7; i++) {
System.out.println(df.format(c.getTime()));
c.add(Calendar.DATE, 1);
}
With the new date and time API in Java 8 you would do:
LocalDate now = LocalDate.now();
// determine country (Locale) specific first day of current week
DayOfWeek firstDayOfWeek = WeekFields.of(Locale.getDefault()).getFirstDayOfWeek();
LocalDate startOfCurrentWeek = now.with(TemporalAdjusters.previousOrSame(firstDayOfWeek));
// determine last day of current week
DayOfWeek lastDayOfWeek = firstDayOfWeek.plus(6); // or minus(1)
LocalDate endOfWeek = now.with(TemporalAdjusters.nextOrSame(lastDayOfWeek));
// Print the dates of the current week
LocalDate printDate = startOfCurrentWeek;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE dd/MM/yyyy");
for (int i=0; i < 7; i++) {
System.out.println(printDate.format(formatter));
printDate = printDate.plusDays(1);
}
Java.time
Using java.time library built into Java 8:
import java.time.DayOfWeek;
import java.time.LocalDate;
import static java.time.temporal.TemporalAdjusters.previousOrSame;
import static java.time.temporal.TemporalAdjusters.nextOrSame;
LocalDate now = LocalDate.now(); # 2015-11-23
LocalDate first = now.with(previousOrSame(DayOfWeek.MONDAY)); # 2015-11-23
LocalDate last = now.with(nextOrSame(DayOfWeek.SUNDAY)); # 2015-11-29
You can iterate over DayOfWeek.values() to get all current week days
DayOfWeek.values(); # Array(MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY)
for (DayOfWeek day: DayOfWeek.values()) {
System.out.print(first.with(nextOrSame(day)));
} # 2015-11-23, 2015-11-24, 2015-11-25, 2015-11-26, 2015-11-27, 2015-11-28, 2015-11-29
First day of this week.
Calendar c = Calendar.getInstance();
while (c.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
c.add(Calendar.DATE, -1);
}
Simply setting the day of week does not seem to be reliable. Consider the following simple code:
Calendar calendar = Calendar.getInstance(Locale.GERMANY);
calendar.set(2011, Calendar.SEPTEMBER, 18);
System.out.printf("Starting day: %tF%n", calendar);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.printf("Last monday: %tF%n", calendar);
System.out.printf("First day of week: %d%n", calendar.getFirstDayOfWeek());
The result of running this program is:
Starting day: 2011-09-18
Last monday: 2011-09-19
First day of week: 2
In other words, it stepped forward in time. For a German locale, this is really not the expected answer. Note that the calendar correctly uses Monday as first day of the week (only for computing the week of the year, perhaps).
You can build up on this: The following code prints the first and last dates of each week for 15 weeks from now.
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
for(int i=0; i<15; i++)
{
System.out.print("Start Date : " + c.getTime() + ", ");
c.add(Calendar.DAY_OF_WEEK, 6);
System.out.println("End Date : " + c.getTime());
c.add(Calendar.DAY_OF_WEEK, 1);
}
If you know which day it is (Friday) and the current date (June 11), you can calculate the other days in this week.
I recommend that you use Joda Time library. Gregorian Calendar class has weekOfWeekyear and dayOfWeek methods.
Calendar startCal = Calendar.getInstance();
startCal.setTimeInMillis(startDate);
Calendar endCal = Calendar.getInstance();
endCal.setTimeInMillis(endDate);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMMM-yyyy");
while (startCal.before(endCal)) {
int weekNumber = startCal.get(Calendar.WEEK_OF_YEAR);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
cal.set(Calendar.WEEK_OF_YEAR, weekNumber);
Date sunday = cal.getTime();
Log.d("sunday", "" + sdf.format(sunday));
cal.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
cal.set(Calendar.WEEK_OF_YEAR, weekNumber);
Date saturday = cal.getTime();
Log.d("saturday", "" + sdf.format(saturday));
weekNumber = weekNumber + 1;
startCal.set(Calendar.WEEK_OF_YEAR, weekNumber);
}
Yes. Use Joda Time
http://joda-time.sourceforge.net/
The algorithm you're looking for (calculating the day of the week for any given date) is "Zeller's Congruence". Here's a Java implementation:
http://technojeeves.com/joomla/index.php/free/57-zellers-congruence

Categories