This question already has answers here:
Strange behaviour with GregorianCalendar
(8 answers)
Closed 4 years ago.
We are using the below code snippet to get number of days for the provided month and year. For 02 and 2011, It returns the no of days as 31 ( which is not the case). for 02 and 2016, it returns the no of days as 29.
Any clues.
package Processes.BSAInvoiceInquiry.ExternalCall.PaymentStatusInquiry;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class PaymentStatusInquiryJavaCode {
protected int year = 0;
protected int month = 0;
protected int days = 0;
public void invoke() throws Exception {
PaymentStatusInquiryJavaCode a = new PaymentStatusInquiryJavaCode();
System.out.println("Year " + year);
System.out.println("Month " + month);
Calendar calObj = new GregorianCalendar();
calObj.set(Calendar.YEAR, year);
calObj.set(Calendar.MONTH, month - 1);
System.out.println("Month " + Calendar.MONTH);
int numDays = calObj.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println("No of the days in the month is " + numDays);
days = numDays;
}
}
This is just another unexpected behavior of Calendar, see this, you can fix it by clear after the creation:
Calendar calendar = new GregorianCalendar();
calendar.clear();
calendar.set(Calendar.YEAR, 2011);
calendar.set(Calendar.MONTH, 1);
System.out.println(calendar.getActualMaximum(calendar.DAY_OF_MONTH)); //28
The use of outdated Calendar should be avoided. In java8, this can be done by:
YearMonth yearMonth = YearMonth.of(2011, 2);
int lengthOfMonth = yearMonth.lengthOfMonth();
System.out.println(lengthOfMonth); //28
To complete user6690200's answer it returns 29 for 2016 because it's the 29th today and 2016 was a leap year and had a 29th of february. 2011 wasn't a leap year so it actually returns the number for the next month(March which has 31 days).
try
// month 1 based
new Calendar.Builder().setDate(year, month-1, 1).build().getActualMaximum(DAY_OF_MONTH)
the problem is none
calObj.set(DAY_OF_MONTH, 1);
Related
I want to retrieve same day previous year.
e.g. today is 2019-03-30 that is year 2019, week 26(week of year), day 7 (day of week).
I need to construct LocalDate which is year 2018, week 26(week of year), day 7 (day of week).
I could not find from java.time package which can built LocalDate like this.
It seems like you want the previous year date with same week of year and day of week as the given date. Below code with give you that result.
LocalDate currentLocalDate = LocalDate.now();
int dayOfWeek = currentLocalDate.getDayOfWeek().getValue();
int weekOfYear = currentLocalDate.get(ChronoField.ALIGNED_WEEK_OF_YEAR);
LocalDate resultLocalDate = currentLocalDate
.minusYears(1)
.with(ChronoField.ALIGNED_WEEK_OF_YEAR, weekOfYear)
.with(ChronoField.DAY_OF_WEEK, dayOfWeek);
Full Example (live copy):
import java.time.*;
import java.time.format.*;
import java.time.temporal.*;
class Example
{
private static void showDateInfo(LocalDate ld) {
int weekOfYear = ld.get(ChronoField.ALIGNED_WEEK_OF_YEAR);
int dayOfWeek = ld.getDayOfWeek().getValue();
System.out.println(ld.format(DateTimeFormatter.ISO_LOCAL_DATE) + " is week " + weekOfYear + ", day " + dayOfWeek);
}
public static void main (String[] args) throws java.lang.Exception
{
LocalDate currentLocalDate = LocalDate.of(2019, 6, 30);
showDateInfo(currentLocalDate);
int dayOfWeek = currentLocalDate.getDayOfWeek().getValue();
int weekOfYear = currentLocalDate.get(ChronoField.ALIGNED_WEEK_OF_YEAR);
LocalDate resultLocalDate = currentLocalDate
.minusYears(1)
.with(ChronoField.ALIGNED_WEEK_OF_YEAR, weekOfYear)
.with(ChronoField.DAY_OF_WEEK, dayOfWeek);
showDateInfo(resultLocalDate);
}
}
Output:
2019-06-30 is week 26, day 7
2018-07-01 is week 26, day 7
I believe that the other answers are close but not quite there yet. As far as I understand, you want to use the week scheme of the default locale, which the other answers don’t do. My suggestion is:
WeekFields wf = WeekFields.of(Locale.getDefault());
LocalDate today = LocalDate.now(ZoneId.of("Africa/Casablanca"));
int week = today.get(wf.weekOfYear());
int dow = today.get(wf.dayOfWeek());
System.out.println("Today is " + today + ", "
+ today.getDayOfWeek() + " of week " + week);
LocalDate correspondingDayLastYear = today.minusYears(1)
.with(wf.weekOfYear(), week)
.with(wf.dayOfWeek(), dow);
System.out.println("Last year was " + correspondingDayLastYear + ", "
+ correspondingDayLastYear.getDayOfWeek()
+ " of week " + correspondingDayLastYear.get(wf.weekOfYear()));
When running on my computer just now the output was:
Today is 2019-06-30, SUNDAY of week 26
Last year was 2018-07-01, SUNDAY of week 26
When I set my locale to US I get the same date, but a different week number since American weeks are defined differently:
Today is 2019-06-30, SUNDAY of week 27
Last year was 2018-07-01, SUNDAY of week 27
I believe that there will also be cases where different locales will give you different dates.
wf.dayOfWeek() gives you a field that numbers the days from 1 to 7 according to the first day of week in that particular locale. It’s important not just to use withDayOfWeek or equivalent, or you would risk sliding into a different week if not using ISO weeks.
Still my answer will not work always! If today is within week 53 of the year, it may very well be that last year didn’t have a week 53. Not much we can do about that. Another problem we can’t solve: In American weeks week 1 starts on January 1. If this is a Sunday, it is the first day for the week, but then week 1 of the previous year started on a Friday or Saturday, so week 1 didn’t have any Sunday.
If you're looking for an ISO week-year compatible function, this is working for me - so far =].
public class FiscalDateUtil {
private static Logger log = LoggerFactory.getLogger(FiscalDateUtil.class);
static public LocalDate previousYearComparisonDate(LocalDate date) {
final int weekYear = date.get(IsoFields.WEEK_BASED_YEAR);
final int weekLastYear = weekYear-1;
final DayOfWeek dayOfWeek = date.getDayOfWeek();
final int weekOfYear = date.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR);
final LocalDate adjustedLastYear = date
.with(IsoFields.WEEK_BASED_YEAR, weekLastYear)
.with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, weekOfYear)
.with(TemporalAdjusters.nextOrSame(dayOfWeek));
if (log.isTraceEnabled()) {
log.trace("starting date {}", date.toString());
log.trace("starting date dow {}", date.getDayOfWeek());
log.trace("lastYear {}", weekLastYear);
log.trace("lastYear dow {}", dayOfWeek);
log.trace("adjustedLastYear {}", adjustedLastYear.toString());
log.trace("adjustedLastYear dow {}", adjustedLastYear.getDayOfWeek());
}
return adjustedLastYear;
}
}
You can add the number of days since beginning of year of the current date to the beginning of the year before.
This should do the trick:
String dateStr = "2019-03-30";
LocalDate date = LocalDate.parse(dateStr);
LocalDate newDate = LocalDate.parse(date.getYear() + "-01-01").plusDays(date.getDayOfYear());
System.out.println(newDate);
I want to calculate the difference between 2 dates in months and days, I don't want to consider a month is 30 days and get the time in milliseconds and convert them, and I don't want to use a library such as Joda, and I also found a solution that uses LocalDate, however I am using Java 7.
I looked for answers to my question but could not find any, and I tried many approaches, I tried creating a calendar and passed the time in milliseconds the difference between my 2 dates, but if I tried for example getting the difference between 15/04 and 15/5 I would get 30 days and not 1 month, below is the code
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, 2013);
c.set(Calendar.MONTH, Calendar.APRIL);
c.set(Calendar.DAY_OF_MONTH, 15);
Date startDate = c.getTime();
c.set(Calendar.YEAR, 2013);
c.set(Calendar.MONTH, Calendar.MAY);
c.set(Calendar.DAY_OF_MONTH, 15);
Date lastDate = c.getTime();
Calendar diffCal = Calendar.getInstance();
diffCal.setTimeInMillis(lastDate.getTime() - startDate.getTime());
int months = ((diffCal.get(Calendar.YEAR) - 1970) * 12) + diffCal.get(Calendar.MONTH);
int days = diffCal.get(Calendar.DAY_OF_MONTH) - 1;
System.out.println("month(s) = " + months); // month(s) = 0
System.out.println("day(s) = " + days); // day(s) = 30
What can I use to get the difference in months first then in days between 2 dates?
EDIT: I wrote the below code and seems to give me what I want, could this be used
Date startDate = sdf.parse("31/05/2016");
Date endDate = sdf.parse("1/06/2016");
Calendar startCalendar = Calendar.getInstance();
Calendar endCalendar = Calendar.getInstance();
startCalendar.setTime(startDate);
endCalendar.setTime(endDate);
int months = 0, days = 0;
months += ((endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR)) * 12);
int startDays = startCalendar.get(Calendar.DAY_OF_MONTH);
int endDays = endCalendar.get(Calendar.DAY_OF_MONTH);
if(endDays >= startDays) {
months += (endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH));
days += (endDays - startDays);
} else {
months += (endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH) - 1);
days += ((startCalendar.getActualMaximum(Calendar.DAY_OF_MONTH) - startDays) + endDays);
}
System.out.println("Difference");
System.out.println("Month(s): " + months);
System.out.println("Day(s): " + days);
You answered your own question in your research. JDK7 does not support what you want. You have three options:
Write your own (do not do this because you will make many mistakes that have been made before)
Use a library like Joda-Time which has been recommended many times
Upgrade to JDK8 and use java.time.Period
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);
This question already has answers here:
Julian day of the year in Java
(9 answers)
Closed 5 years ago.
I want to get the number of day.. i.e.
Jan 1 is day 1
jan 2 is day 2
Feb 1 is day 32 and december 31 is day 365 or 366 depending on leap year or not
i have used all kind of techniques such as date1 - date2 etc...
but nothing seems to work for me cant get the logic right may be.. what i want is count and add the number of the months that has gone past plus the number days of the running month i.e today is 21st Sept 2012 is day number (31(jan)+29(feb)+31(mar)+30(apr)+31(may)+30(june)+31(july)+31(aug)+20(sept)) = 264th day and they will keep adding plus one every time a day go past... thanks
mycode
int year = Calendar.getInstance().get(Calendar.YEAR);
GregorianCalendar gc = new GregorianCalendar();
gc.set(GregorianCalendar.DAY_OF_MONTH, 8);
gc.set(GregorianCalendar.MONTH, GregorianCalendar.JUNE);
gc.set(GregorianCalendar.YEAR, year);
int numberofDaysPassed=gc.get(GregorianCalendar.DAY_OF_YEAR);
numberofDaysPassed is giving me 160, undesired result
Calendar calendar = Calendar.getInstance();
int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
Or using Joda-API
DateTime dt = new DateTime();
int dayOfYear = dt.getDayOfYear();
If you need 'th' part, use switch statement
switch (dayOfYear > 20 ? (dayOfYear % 10) : dayOfYear) {
case 1: return dayOfYear + "st";
break;
case 2: return dayOfYear + "nd";
break;
case 3: return dayOfYear + "rd";
break;
default: return dayOfYear + "th";
break;
}
LocalDate
Use the LocalDate class in java.time package built into Java 8 and later.
Get the day-of-year:
int dayOfYear = LocalDate.now().getDayOfYear();
…and set the day-of-year:
LocalDate localDate = LocalDate.now().withDayOfYear( 195 );
Try setting the date on the calendar to the date in the problem, you asked for 21st Sept but you put 8th of June in the code.
Here is the updated code that gives 265 instead:
int year = Calendar.getInstance().get(Calendar.YEAR);
GregorianCalendar gc = new GregorianCalendar();
gc.set(Calendar.DAY_OF_MONTH, 21); // you asked for 21st Sept but put 8
gc.set(Calendar.MONTH, Calendar.SEPTEMBER); // you aksed for 21st Sept but put JUNE
gc.set(Calendar.YEAR, year);
int numberofDaysPassed = gc.get(Calendar.DAY_OF_YEAR);
System.out.println(numberofDaysPassed);
By the way you don't need to set the month, day etc. on Calendar, it defaults to 'now'...
Using Java 8 you can do this:
int n = LocalDate.now().get(ChronoField.DAY_OF_YEAR);
Calendar ca1 = Calendar.getInstance();
int DAY_OF_YEAR=ca1.get(Calendar.DAY_OF_YEAR);
System.out.println("Day of Year :"+DAY_OF_YEAR);
Check the result in your logcat..
DateTime dt = new DateTime();
String dayOfYear = dt.getDayOfYear().toString();
String day = "";
if(dayOfYear.endsWith("1") && !dayOfYear.endsWith("11"))
day = dayOfYear+"st";
else if(dayOfYear.endsWith("2") && !dayOfYear.endsWith("12"))
day = dayOfYear+"nd";
else if(dayOfYear.endsWith("3") && !dayOfYear.endsWith("13"))
day = dayOfYear+"rd";
else
day = dayOfYear+"th";
System.out.println("Day of year :- "+ day);
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);