Same day prevous year (previous year, same week and day of week) - java

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);

Related

Java - Getting same day of week for next year

I was looking for a way to make optimum of Java 8's LocalDate to find next year's date which falls on same day of week.
For example today is 1rd March 2022 - Tuesday. Assume this is the input date, the the output date that I expect to get is 28th Feb 2023, because its the same day (Tuesday) for next year
One option that I tried was adding 364 days as shown in the example
public static void main(String args[]){
LocalDate currentDate= LocalDate.now();
System.out.println("Current Date: " + currentDate + " Day" currentDate.getDayOfWeek().name());
System.out.println("Next Year's date: " + currentDate.plusDays(364) + " Next year day: " +currentDate.plusDays(364).getDayOfWeek().name());
}
This works but may have drawback with leap years.
Other option is to add 1 year to current date and do a while loop check for dayOfWeek for each day - 1
Is there a better way to do this?

Is there a built in function (Java) for an Android app to get the date range of the week of the current date ("today") [duplicate]

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);

Java: check if a given date is within current month

I need to check if a given date falls in the current month, and I wrote the following code, but the IDE reminded me that the getMonth() and getYear() methods are obsolete. I was wondering how to do the same thing in newer Java 7 or Java 8.
private boolean inCurrentMonth(Date givenDate) {
Date today = new Date();
return givenDate.getMonth() == today.getMonth() && givenDate.getYear() == today.getYear();
}
//Create 2 instances of Calendar
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
//set the given date in one of the instance and current date in the other
cal1.setTime(givenDate);
cal2.setTime(new Date());
//now compare the dates using methods on Calendar
if(cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)) {
if(cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH)) {
// the date falls in current month
}
}
java.time (Java 8)
There are several ways to do it with the new java.time API (tutorial). You can do it using .get(ChronoField.XY), but I think this is prettier:
Instant given = givenDate.toInstant();
Instant ref = Instant.now();
return Month.from(given) == Month.from(ref) && Year.from(given).equals(Year.from(ref));
For better re-usability you can also refactor this code to "temporal query":
public class TemporalQueries {
//TemporalQuery<R> { R queryFrom(TemporalAccessor temporal) }
public static Boolean isCurrentMonth(TemporalAccessor temporal) {
Instant ref = Instant.now();
return Month.from(temporal) == Month.from(ref) && Year.from(temporal).equals(Year.from(ref));
}
}
Boolean result = givenDate.toInstant().query(TemporalQueries::isCurrentMonth); //Lambda using method reference
Time Zone
The other answers ignore the crucial issue of time zone. A new day dawns earlier in Paris than in Montréal. So at the same simultaneous moment, the dates are different, "tomorrow" in Paris while "yesterday" in Montréal.
Joda-Time
The java.util.Date and .Calendar classes bundled with Java are notoriously troublesome, confusing, and flawed. Avoid them.
Instead use either Joda-Time library or the java.time package in Java 8 (inspired by Joda-Time).
Here is example code in Joda-Time 2.5.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTime = new DateTime( yourJUDate, zone ); // Convert java.util.Date to Joda-Time, and assign time zone to adjust.
DateTime now = DateTime.now( zone );
// Now see if the month and year match.
if ( ( dateTime.getMonthOfYear() == now.getMonthOfYear() ) && ( dateTime.getYear() == now.getYear() ) ) {
// You have a hit.
}
For a more general solution to see if a moment falls within any span of time (not just a month), search StackOverflow for "joda" and "interval" and "contain".
java.time (Java 8)
Java 8 provides the YearMonth class which represents a given month within a given year (e.g. January 2018). This can be used to compare against the YearMonth of the given date.
private boolean inCurrentMonth(Date givenDate) {
ZoneId timeZone = ZoneOffset.UTC; // Use whichever time zone makes sense for your use case
LocalDateTime givenLocalDateTime = LocalDateTime.ofInstant(givenDate.toInstant(), timeZone);
YearMonth currentMonth = YearMonth.now(timeZone);
return currentMonth.equals(YearMonth.from(givenLocalDateTime));
}
Note that this approach will work for any of the Java 8 time classes that have both a month and a date part (LocalDate, ZonedDateTime, etc.) and not just LocalDateTime.
As far as I know the Calendar class and all derived from it return the date using the get(). See the documentation for this class. Also here is an example taken from here:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd HH:mm:ss");
Calendar calendar = new GregorianCalendar(2013,1,28,13,24,56);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH); // Jan = 0, dec = 11
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
int weekOfMonth= calendar.get(Calendar.WEEK_OF_MONTH);
int hour = calendar.get(Calendar.HOUR); // 12 hour clock
int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY); // 24 hour clock
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
int millisecond= calendar.get(Calendar.MILLISECOND);
System.out.println(sdf.format(calendar.getTime()));
System.out.println("year \t\t: " + year);
System.out.println("month \t\t: " + month);
System.out.println("dayOfMonth \t: " + dayOfMonth);
System.out.println("dayOfWeek \t: " + dayOfWeek);
System.out.println("weekOfYear \t: " + weekOfYear);
System.out.println("weekOfMonth \t: " + weekOfMonth);
System.out.println("hour \t\t: " + hour);
System.out.println("hourOfDay \t: " + hourOfDay);
System.out.println("minute \t\t: " + minute);
System.out.println("second \t\t: " + second);
System.out.println("millisecond \t: " + millisecond);
which outputs
2013 Feb 28 13:24:56
year : 2013
month : 1
dayOfMonth : 28
dayOfWeek : 5
weekOfYear : 9
weekOfMonth : 5
hour : 1
hourOfDay : 13
minute : 24
second : 56
millisecond : 0
I think it was replaced because the new way offers a much simpler handling using a single function, which is much easier to remember.

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);

Android SimpleDateFormat problem

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = (Date)formatter.parse("2011-09-13");
Log.e(MY_DEBUG_TAG, "Output is "+ date.getYear() + " /" + date.getMonth() + " / "+ (date.getDay()+1));
Is out putting
09-13 14:20:18.740: ERROR/GoldFishActivity(357): Output is 111 /8 / 3
What is the issue?
The methods you are using in the Date class are deprecated.
You get 111 for the year, because getYear() returns a value that is the result of subtracting 1900 from the year i.e. 2011 - 1900 = 111.
You get 3 for the day, because getDay() returns the day of the week and 3 = Wednesday. getDate() returns the day of the month, but this too is deprecated.
You should use the Calendar class instead.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = (Date)formatter.parse("2011-09-13");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
Log.e(MY_DEBUG_TAG, "Output is "+ cal.get(Calendar.YEAR)+ " /" + (cal.get(Calendar.MONTH)+1) + " / "+ cal.get(Calendar.DAY_OF_MONTH));
Read the javadoc of java.util.Date carefully.
getYear returns the number of years since 1900.
getMonth returns the month, starting from 0 (0 = January, 1 = February, etc.).
getDay returns the day of week (0 = Sunday, 1 = Monday, etc.), not the day of month.
And all these methods are deprecated. You shouldn't use them anymore.

Categories