Java Calendar: calculate start date and end date of the previous week - java

What is most convenient and shortest way to get start and end dates of the previous week?
Example: today is 2011-10-12 (input data),but I want to get 2011-10-03 (Monday's date of previous week) and 2011-10-09 (Sunday's date of previous week).

Here's another JodaTime solution. Since you seem to want Dates only (not timestamps), I'd use the DateMidnight class:
final DateTime input = new DateTime();
System.out.println(input);
final DateMidnight startOfLastWeek =
new DateMidnight(input.minusWeeks(1).withDayOfWeek(DateTimeConstants.MONDAY));
System.out.println(startOfLastWeek);
final DateMidnight endOfLastWeek = startOfLastWeek.plusDays(6);
System.out.println(endOfLastWeek);
Output:
2011-10-12T18:13:50.865+02:00
2011-10-03T00:00:00.000+02:00
2011-10-10T00:00:00.000+02:00

public static Calendar firstDayOfLastWeek(Calendar c) {
c = (Calendar) c.clone();
// last week
c.add(Calendar.WEEK_OF_YEAR, -1);
// first day
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
return c;
}
public static Calendar lastDayOfLastWeek(Calendar c) {
c = (Calendar) c.clone();
// first day of this week
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
// last day of previous week
c.add(Calendar.DAY_OF_MONTH, -1);
return c;
}

I would go for #maerics answer if third party library is not involved. I have to replace roll() method with add() method as roll will leave the higher field unchanged. e.g., 22nd August will be obtained from 1st August being rolled -7 days. Note the month remain unchanged.
The source code goes as below.
public static Calendar[] getLastWeekBounds(Calendar c) {
int cdow = c.get(Calendar.DAY_OF_WEEK);
Calendar lastMon = (Calendar) c.clone();
lastMon.add(Calendar.DATE, -7 - (cdow - Calendar.MONDAY));
Calendar lastSun = (Calendar) lastMon.clone();
lastSun.add(Calendar.DATE, 6);
return new Calendar[] { lastMon, lastSun };
}

You can use the Calendar.roll(int,int) method with arguments Calendar.DATE and an offset for the current day of week:
public static Calendar[] getLastWeekBounds(Calendar c) {
int cdow = c.get(Calendar.DAY_OF_WEEK);
Calendar lastMon = (Calendar) c.clone();
lastMon.roll(Calendar.DATE, -7 - (cdow - Calendar.MONDAY));
Calendar lastSun = (Calendar) lastMon.clone();
lastSun.roll(Calendar.DATE, 6);
return new Calendar[] { lastMon, lastSun };
}
This function returns an array of two Calendars, the first being last week's Monday and last week's Sunday.
Wow, the Java date APIs are terrible.

Calendar today = Calendar.getInstance();
Calendar lastWeekSunday = (today.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) ? today.roll(-7): today.roll(Calendar.DAY_OF_YEAR, Calendar.SUNDAY - today.get(Calendar.DAY_OF_WEEK));
Calendar lastWeekMonday = lastWeekSunday.roll( Calendar.DAY_OF_YEAR, -6 );

Using Joda:
DateTime input;
DateTime startOfLastWeek = input.minusWeeks(1).minusDays(input.getDayOfWeek()-1);
DateTime endOfLastWeek = input.minusWeeks(1).plusDays(input.getDayOfWeek()+1);
DateTime endOfLastWeek = startOfLastWeek.plusDays(6);
EDIT:
Joda does not allow a different first day of the week, but strictly sticks to the ISO standard, which states that a week always starts on Monday. However, if you need to make that configurable, you could pass the desired first day of the week as a parameter. See the above link for some other ideas.
public DateTime getFirstDayOfPreviousWeek(DateTime input)
{
return getFirstDayOfPreviousWeek(input, DateTimeConstants.MONDAY);
}
public DateTime getFirstDayOfPreviousWeek(DateTime input, int firstDayOfWeek)
{
return new DateTime(input.minusWeeks(1).withDayOfWeek(firstDayOfWeek));
}
public DateTime getLastDayOfPreviousWeek(DateTime input)
{
return getLastDayOfPreviousWeek(input, DateTimeConstants.MONDAY);
}
public DateTime getLastDayOfPreviousWeek(DateTime input, int firstDayOfWeek)
{
return new DateTime(getFirstDayOfPreviousWeek(input, firstDayOfWeek).plusDays(6));
}

Related

Adding date in Gregorian Calendar

import java.util.GregorianCalendar;
public class CalendarMain {
public static void main(String[] args) {
GregorianCalendar calendar = new GregorianCalendar();
int month = calendar.get(GregorianCalendar.MONTH)+1;
int year = calendar.get(GregorianCalendar.YEAR);
int weekday = calendar.get(GregorianCalendar.DAY_OF_WEEK);
int dayOfMonth = calendar.get(GregorianCalendar.DAY_OF_MONTH);
System.out.println(month+"/"+dayOfMonth+"/"+year);
calendar.add(GregorianCalendar.DAY_OF_MONTH, 10);
System.out.println(GregorianCalendar.DAY_OF_MONTH);
}
}
I am trying to add 10 days to the current date but am getting a weird problem. It does not seem to be adding correctly.
Output:
9/18/2014
5
// Get a calendar which is set to a specified date.
Calendar calendar = new GregorianCalendar(2014, Calendar.JANUARY, 1);
// Get the current date representation of the calendar.
Date startDate = calendar.getTime();
// Increment the calendar's date by 1 day.
calendar.add(Calendar.DAY_OF_MONTH, 1);
// Get the current date representation of the calendar.
Date endDate = calendar.getTime();
System.out.println(startDate);
System.out.println(endDate);
I think the last row is wrong, try this:
System.out.println(calendar.get(GregorianCalendar.DAY_OF_MONTH));
Use
System.out.println(calendar.get(GregorianCalendar.DAY_OF_MONTH));
instead of
System.out.println(GregorianCalendar.DAY_OF_MONTH);
Output :
9/18/2014
28
What you were doing in your code is printing the integer code of GregorianCalendar.DAY_OF_MONTH final variable, Which will remain 5, no matter what you have added in calendar. You were needed to use calendar.get(...) function to get the date of month of this calendar.

Get the first Monday of a month

I want to get the day on which the first Monday of a specific month/year will be.
What I have:
I basically have two int variables, one representing the year and one representing the month.
What I want to have:
I want to know the first Monday in this month, preferably as an int or Integer value.
For example:
I have 2014 and 1 (January), the first Monday in this month was the 6th, so I want to return 6.
Problems:
I thought I could do that with the Calendar but I am already having trouble setting up the calendar with only Year and Month available. Furthermore, I'm not sure how to actually return the first Monday of the month/year with Calendar.
I already tried this:
Calendar cal = Calendar.getInstance();
cal.set(this.getYear(),getMonth(), 1);
int montag = cal.getFirstDayOfWeek();
for( int j = 0; j < 7; j++ ) {
int calc = j - montag;
if( calc < 0 ) {
calc += 6;
}
weekDays[calc].setText(getDayString(calc));
}
Java.time
Use java.time library built into Java 8 and TemporalAdjuster. See Tutorial.
import java.time.DayOfWeek;
import java.time.LocalDate;
import static java.time.temporal.TemporalAdjusters.firstInMonth;
LocalDate now = LocalDate.now(); //2015-11-23
LocalDate firstMonday = now.with(firstInMonth(DayOfWeek.MONDAY)); //2015-11-02 (Monday)
If you need to add time information, you may use any available LocalDate to LocalDateTime conversion like
firstMonday.atStartOfDay() # 2015-11-02T00:00
getFirstDayOfWeek() returns which day is used as the start for the current locale. Some people consider the first day Monday, others Sunday, etc.
This looks like you'll have to just set it for DAY_OF_WEEK = MONDAY and DAY_OF_WEEK_IN_MONTH = 1 as that'll give you the first Monday of the month. To do the same for the year, first set the MONTH value to JANUARY then repeat the above.
Example:
private static Calendar cacheCalendar;
public static int getFirstMonday(int year, int month) {
cacheCalendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
cacheCalendar.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
cacheCalendar.set(Calendar.MONTH, month);
cacheCalendar.set(Calendar.YEAR, year);
return cacheCalendar.get(Calendar.DATE);
}
public static int getFirstMonday(int year) {
return getFirstMonday(year, Calendar.JANUARY);
}
Here's a simple JUnit that tests it: http://pastebin.com/YpFUkjQG
First of all you should know the latest version of java i.e. JAVA8
Get familiar with LocalDate in JAVA8
Then only go through below code
public class Test {
public static void main(String[] args) {
LocalDate date=LocalDate.of(2014,1, 1);
for(int i=0;i<date.lengthOfMonth();i++){
if("Monday".equalsIgnoreCase(date.getDayOfWeek().toString())){
break;
}else{
date=date.plusDays(1);
}
}
System.out.println(date.getDayOfMonth());
}
}
Joda-Time
The Joda-Time library offers a class, LocalDate, for when you need only a date without a time-of-day. The method getDayOfWeek returns a number you can compare to the constant MONDAY.
LocalDate localDate = new LocalDate( year, month, 1 );
while ( localDate.getDayOfWeek() != DateTimeConstants.MONDAY ) {
localDate = localDate.plusDays( 1 );
}
int firstMonday = localDate.getDayOfMonth();
Immutable Syntax
For thread-safety, Joda-Time uses immutable objects. So rather than modify field values in an existing object, we create a new instance based on the original.
java.time
As another answer by Abhishek Mishra says, the new java.time package bundled with Java 8 also offers a LocalDate class similar to Joda-Time.
The method getFirstDayOfWeek() is not helpful. Quoting its javadoc:
Gets what the first day of the week is; e.g., SUNDAY in the U.S., MONDAY in France
The following tested method uses modulus arithmetic to find the day of the month of the first Monday:
public static long getMondaysDay(int year, int month) {
try {
Date d = new SimpleDateFormat("d-M-yyyy").parse("1-" + month + "-" + year);
long epochMillis = d.getTime() + TimeZone.getDefault().getOffset(d.getTime());
return (12 - TimeUnit.MILLISECONDS.toDays(epochMillis) % 7) % 7;
} catch (ParseException ignore) { return 0; } // Never going to happen
}
Knowing that the first day of the epoch was Thursday, this works by using modulus arithmetic to calculate the day of the epoch week, then how many days until the next Monday, then modulus again in case the first falls before Thursday. The magic number 12 is 4 (the number of days from Thursday to Monday) plus 1 because days of the month start from 1 plus 7 to ensure positive results after subtraction.
The simplest way is:
LocalDate firstSundayOfNextMonth = LocalDate
.now()
.with(firstDayOfNextMonth())
.with(nextOrSame(DayOfWeek.MONDAY));
Here is a general function to get the nth DAY_OF_WEEK of a given month. You can use it to get the first Monday of any given month.
import java.util.Calendar;
public class NthDayOfWeekOfMonth {
public static void main(String[] args) {
// get first Monday of July 2019
Calendar cal = getNthDayOfWeekOfMonth(2019,Calendar.JULY,1,Calendar.MONDAY);
System.out.println(cal.getTime());
// get first Monday of August 2019
cal = getNthDayOfWeekOfMonth(2019,Calendar.AUGUST,1,Calendar.MONDAY);
System.out.println(cal.getTime());
// get third Friday of September 2019
cal = getNthDayOfWeekOfMonth(2019,Calendar.SEPTEMBER,3,Calendar.FRIDAY);
System.out.println(cal.getTime());
}
public static Calendar getNthDayOfWeekOfMonth(int year, int month, int n, int dayOfWeek) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE,0);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.YEAR,year);
cal.set(Calendar.MONTH,month);
cal.set(Calendar.DAY_OF_MONTH,1);
int dayDiff = dayOfWeek-cal.get(Calendar.DAY_OF_WEEK);
if (dayDiff<0) {
dayDiff+=7;
}
dayDiff+=7*(n-1);
cal.add(Calendar.DATE, dayDiff);
return cal;
}
}
Output:
Mon Jul 01 00:00:00 EDT 2019
Mon Aug 05 00:00:00 EDT 2019
Fri Sep 20 00:00:00 EDT 2019
Lamma Date library is very good for this use case.
#Test
public void test() {
assertEquals(new Date(2014, 1, 6), firstMonday(2014, 1));
assertEquals(new Date(2014, 2, 3), firstMonday(2014, 2));
assertEquals(new Date(2014, 3, 3), firstMonday(2014, 3));
assertEquals(new Date(2014, 4, 7), firstMonday(2014, 4));
assertEquals(new Date(2014, 5, 5), firstMonday(2014, 5));
assertEquals(new Date(2014, 6, 2), firstMonday(2014, 6));
}
public Date firstMonday(int year, int month) {
Date firstDayOfMonth = new Date(year, month, 1);
return firstDayOfMonth.nextOrSame(DayOfWeek.MONDAY);
}
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("MMM/dd/YYYY");
calendar.set(Calendar.MONTH,Calendar.JUNE);
calendar.set(Calendar.DAY_OF_MONTH,1);
int day = (Calendar.TUESDAY-calendar.get(Calendar.DAY_OF_WEEK));
if(day<0){
calendar.add(Calendar.DATE,7+(day));
}else{
calendar.add(Calendar.DATE,day);
}
System.out.println("First date is "+sdf.format(calendar.getTime()));
Get the All Monday of a month
public class AllMonday {
public static void main(String[] args){
System.out.println(weeksInCalendar(YearMonth.now()));
}
public static List<LocalDate> weeksInCalendar(YearMonth month) {
List<LocalDate> firstDaysOfWeeks = new ArrayList<>();
for (LocalDate day = firstDayOfCalendar(month);
stillInCalendar(month, day); day = day.plusWeeks(1)) {
firstDaysOfWeeks.add(day);
}
return firstDaysOfWeeks;
}
private static LocalDate firstDayOfCalendar(YearMonth month) {
DayOfWeek FIRST_DAY_OF_WEEK = DayOfWeek.of(1);
System.out.println( month.atDay(1).with(FIRST_DAY_OF_WEEK));
return month.atDay(1).with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY));
}
private static boolean stillInCalendar(YearMonth yearMonth, LocalDate day) {
System.out.println(!day.isAfter(yearMonth.atEndOfMonth()));
return !day.isAfter(yearMonth.atEndOfMonth());
}
}

best way to calculate the first- and last-day of Week, Month and Year

He all,
I am trying to calculate the first- and last-day of Week, Month and Year.
For Month and Year it Works fine but week is wrong:
public Date[] calcDateRange(Calendar c, int day) {
Date[] dr = new Date[2];
// setMin
c.set(day, c.getActualMinimum(day));
dr[0] = c.getTime();
// setMax
c.set(day, c.getActualMaximum(day));
dr[1] = c.getTime();
return dr;
}
public void print() {
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
Calendar cStart = Calendar.getInstance(Locale.GERMANY);
cStart.setFirstDayOfWeek(Calendar.MONDAY);
System.out.println("startdate: " + sdf.format(cStart.getTime()));
Date[] minMaxD = calcDateRange(cStart, Calendar.DAY_OF_WEEK);
System.out.println("start_of_week:\t" + sdf.format(minMaxD[0]) + "\nend_of_week:\t" + sdf.format(minMaxD[1]));
minMaxD = calcDateRange(cStart, Calendar.DAY_OF_MONTH);
System.out.println("start_of_month:\t" + sdf.format(minMaxD[0]) + "\nend_of_month:\t" + sdf.format(minMaxD[1]));
minMaxD = calcDateRange(cStart, Calendar.DAY_OF_YEAR);
System.out.println("start_of_year:\t" + sdf.format(minMaxD[0]) + "\nend_of_year:\t" + sdf.format(minMaxD[1]));
}
Can someone help me to find my mistakes?
What is the best way to calculate the dates?
Output:
startdate: 20.03.2014
start_of_week: 23.03.2014 <--- wrong, should be '17.03.2014'
end_of_week: 22.03.2014 <--- wrong, should be '23.03.2014'
start_of_month: 01.03.2014
end_of_month: 31.03.2014
start_of_year: 01.01.2014
end_of_year: 31.12.2014
Thank you in advance.
//edit
Currently I use the following methode, but im not realy happy with it:
public Date[] calcDateRange(Calendar c, int day) {
int fdow = c.getFirstDayOfWeek();
c.setFirstDayOfWeek(Calendar.SUNDAY);
Date[] dr = new Date[2];
// setMin
c.set(day, c.getActualMinimum(day));
//..setSecondsMinutes
if (day == Calendar.DAY_OF_WEEK)
c.add(day, 1); // German Week correction
dr[0] = c.getTime();
// setMax
c.set(day, c.getActualMaximum(day));
//..setSecondsMinutes
if (day == Calendar.DAY_OF_WEEK)
c.add(day, 1); // German Week correction
dr[1] = c.getTime();
c.setFirstDayOfWeek(fdow);
return dr;
}
Joda Time library is useful for things around dates and times. As I cant comment yet I am posting it as an answer. I suggest you to look into it.
http://www.joda.org/joda-time/
//EDIT:
I think that I have found where is the mistake.
The start of the week is incorrect because:
You call
Date[] minMaxD = calcDateRange(cStart, Calendar.DAY_OF_WEEK);
and then on the line in calcDateRange function
c.set(day, c.getActualMinimum(day));
the following will happen:
the day variable is an int with value 7
c.getActualMinimum(day) will return 1 because of the fact that getActualMinimum(7) method returns the minimum for field 7 which is "DAY_OF_WEEK" and the minimum for this field equals "SUNDAY" which is int with value 1
the you c.set(7,1) which will set the "DAY_OF_WEEK" as 1 ("SUNDAY")
On the
dr[0] = c.getTime();
line you will get time for SUNDAY because you set it and the date then returns 23.3.
Principal is the same for the end of week:
On the line
c.set(day, c.getActualMaximum(day));
you set "DAY_OF_WEEK" to SATURDAY and then it will return you date 22.3.
//EDIT2:
method for calculating start and end of week
public Date[] calcDateRangeWeek(Calendar c, int day) {
Date[] dr = new Date[2];
// setMin
c.set(day, Calendar.MONDAY);
dr[0] = c.getTime();
// setMax
c.set(day, Calendar.SUNDAY);
dr[1] = c.getTime();
return dr;
}
If you can use Java 8, I would use the TemporalAdjusters from java.time:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import static java.time.DayOfWeek.*;
import static java.time.temporal.TemporalAdjusters.*;
public void print() {
DateTimeFormatter german = DateTimeFormatter.ofPattern("dd.MM.yyyy");
LocalDate start = LocalDate.now();
System.out.printf("startdate: %s%n", start.format(german));
System.out.printf("start_of_week:\t%s%nend_of_week:\t%s%n",
start.with(previousOrSame(MONDAY)).format(german),
start.with(nextOrSame(SUNDAY)).format(german));
System.out.printf("start_of_month:\t%s%nend_of_month:\t%s%n",
start.with(firstDayOfMonth()).format(german),
start.with(lastDayOfMonth()).format(german));
System.out.printf("start_of_year:\t%s%nend_of_year:\t%s%n",
start.with(firstDayOfYear()).format(german),
start.with(lastDayOfYear()).format(german));
}
If you can't use Java 8, these features all come from the Joda Time library.
You can use Java Calendar like this
Calendar cal = Calendar.getInstance();
Date now = cal.getTime();
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
Date mondayOfTheWeek = cal.getTime();
....
The calendar recalculate the associated Date automatically
EDIT: for the last day of the month
cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) + 1);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.add(Calendar.DAY_OF_MONTH, -1);
And you can do the same with Calendar.YEAR and Calendar.DAY_OF_YEAR

Compare dates using Calendar class using java

The user entered date is using a drop down separately for day, month and year. I have to compare the user entered date with today's date and check if it is same day or future day. I am a bit confused about the time portion because I am not interested in time, just the date. How to solve this without using the Date class (I read it is not recommended to use Date class).
Thanks.
You first need to create GregorianCalendar instance representing entered date:
Calendar user = new GregorianCalendar(2012, Calendar.MAY, 17);
And one for "now":
Calendar now = new GregorianCalendar();
This will yield positive value if date is in the future and negative - if in the past:
user.compareTo(now);
Few notes about constructing user object:
it uses current JVM time zone, so in my case it is midnight, 17th of May in CEST time zone
be careful with months, they are 0-based
Try class DateUtils of library Apache Commons Lang.
This class provides the method truncatedEquals(cal1, cal2, field).
So you can check for equality with a single line of code:
Calendar user = new GregorianCalendar(2012, Calendar.MAY, 17);
Calendar now = Calendar.getInstance();
if(DateUtils.truncatedEquals(user, now, Calendar.DATE)){
// your code goes here
}
Simple calculation :
GregorianCalendar gc1 = new GregorianCalendar();
GregorianCalendar gc2 = new GregorianCalendar();
gc2.add(GregorianCalendar.DAY_OF_MONTH, 2); // gc2 is 2 days after gc1
long duration = (gc2.getTimeInMillis() - gc1.getTimeInMillis() )
/ ( 1000 * 60 * 60 * 24) ;
System.out.println(duration);
-> 2
Use a gregorian calendar.
If you wanted to know the number of days difference between two dates then you could make a method similar to the following.
public int getDays(GregorianCalendar g1, GregorianCalendar g2) {
int elapsed = 0;
GregorianCalendar gc1, gc2;
if (g2.after(g1)) {
gc2 = (GregorianCalendar) g2.clone();
gc1 = (GregorianCalendar) g1.clone();
}
else {
gc2 = (GregorianCalendar) g1.clone();
gc1 = (GregorianCalendar) g2.clone();
}
gc1.clear(Calendar.MILLISECOND);
gc1.clear(Calendar.SECOND);
gc1.clear(Calendar.MINUTE);
gc1.clear(Calendar.HOUR_OF_DAY);
gc2.clear(Calendar.MILLISECOND);
gc2.clear(Calendar.SECOND);
gc2.clear(Calendar.MINUTE);
gc2.clear(Calendar.HOUR_OF_DAY);
while ( gc1.before(gc2) ) {
gc1.add(Calendar.DATE, 1);
elapsed++;
}
return elapsed;
}
That would return you the difference in the number of days.
Try this solution:
int day = 0; //user provided
int month = 0; //user provided
int year = 0; //user provided
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONDAY, month);
calendar.set(Calendar.DAY_OF_MONTH, day);
long millisUser = calendar.getTime().getTime();
long nowMillis = System.currentTimeMillis();
if(nowMillis < millisUser) {
...
}
Above is check if date is in future.
There is nothing wrong in using java.util.Date
You can use:
int day = 0; //user provided
int month = 0; //user provided
int year = 0; //user provided
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONDAY, month);
calendar.set(Calendar.DAY_OF_MONTH, day);
Date userSubmit = calendar.getTime();
Date now = new Date();
if(userSubmit.after(now)) {
...
}
But if you want fluent, easy and intuitive API with dates I recommend using JodaTime

How to get date of last Friday from specified date? [duplicate]

This question already has answers here:
Time: How to get the next friday?
(9 answers)
Closed 6 years ago.
How can I find out the date of last (previous) "Friday" or any other day from a specified date?
public getDateOnDay(Date date, String dayName) {
// ?
}
I won't give an answer (try it yourself first!), but, maybe these tips can help you out.
You first need to figure out the current day of the week you are on. You may want to take a look at Java's Calendar class to get an idea of how to do that.
Once you get the date you are on, think about the modulus operator and how you can use that to move backwards to pick up the previous day that you are looking for from the day you are currently at. (Remember, a week is 7 days and each day of the week takes up a "slot" in those 7 days.)
Once you have the number of days in between, you'll want to subtract. Of course, there are classes that can add and subtract days for you in the Java framework...
I hope that helps. Again, I encourage you to always try the problem for yourself, first. You learn far much more that way and be a better developer in the long run for it.
Here is a brute force idea. Check if current date is friday. If not, subtract 1 day from today. Check if new date is friday. If not, subtract 1 day from new date..... so on.. you get the idea.
Try this one:
/**
* Return last day of week before specified date.
* #param date - reference date.
* #param day - DoW field from Calendar class.
* #return
*/
public static Date getDateOnDay(Date date, int day) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.WEEK_OF_YEAR, -1);
cal.set(Calendar.DAY_OF_WEEK, day);
return cal.getTime();
}
Good luck.
I'm using this:
private Date getDateOnDay(Date date, int day) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.setFirstDayOfWeek(day);
cal.set(Calendar.DAY_OF_WEEK, day);
return cal.getTime();
}
Get the day of week for the date. Look at Calendar javadoc. Once you have the day of the week you can calculate an offset to apply to the date.
To get any latest date based on weekday:
private String getWeekDayDate(String weekday){
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Calendar start = Calendar.getInstance();
Date now = new Date();
start.setTime(now);
Calendar end = Calendar.getInstance();
end.add(Calendar.DATE, -7);
while (start.after(end))
{
try {
Date temp = start.getTime();
String day = new SimpleDateFormat("EEEE").format(temp);
if(day.equalsIgnoreCase(weekday))
return formatter.format(temp);
}catch(Exception e) {
e.printStackTrace();
}
start.add(Calendar.DAY_OF_YEAR, -1);
}
return null;
}
To get latest Friday date, give weekday as "Friday"
//gets the last four Fridays from today's date if you want pass in a any date
//just need to tweak the code, the other method just basically formats the date in dd/MM/YYYY format.
function GetLastFourFridays() {
today = new Date();
LastFridayDate = new Date();
LastFridayDate.setDate(LastFridayDate.getDate() - 1);
while (LastFridayDate.getDay() != 5) {
LastFridayDate.setDate(LastFridayDate.getDate() - 1);
}
var lfd = LastFridayDate
lfd = convertDate(lfd)
document.getElementById("first_week_th").innerHTML = lfd
LastFridayDate.setDate(LastFridayDate.getDate() - 1);
var friLastWeek = LastFridayDate
while (friLastWeek.getDay() != 5) {
friLastWeek.setDate(friLastWeek.getDate() - 1);
}
var flw = friLastWeek
flw = convertDate(flw)
document.getElementById("second_week_th").innerHTML = flw
friLastWeek.setDate(friLastWeek.getDate() - 1);
var friTwoWeeks = friLastWeek
while (friTwoWeeks.getDay() != 5) {
friTwoWeeks.setDate(friTwoWeeks.getDate() - 1);
}
var ftw = friTwoWeeks
ftw = convertDate(ftw)
document.getElementById("third_week_th").innerHTML = ftw
friTwoWeeks.setDate(friTwoWeeks.getDate() - 1);
var friThreeWeeks = friTwoWeeks
while (friThreeWeeks.getDay() != 5) {
friThreeWeeks.setDate(friThreeWeeks.getDate() - 1);
}
var ftww = friThreeWeeks
ftww = convertDate(ftww)
document.getElementById("fourth_week_th").innerHTML = ftww
}
//convets the date 00//00//0000
function convertDate(inputFormat) {
function pad(s) { return (s < 10) ? '0' + s : s; }
var d = new Date(inputFormat);
return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/');}

Categories

Resources