Get next week and previous week staring and ending dates in java - java

I want to get the starting and ending dates of a week
for example
2012-05-06 to 2012-05-12
2012-05-13 to 2012-05-19
The code I have written is
currWeekCalender.add(Calendar.WEEK_OF_YEAR, 1);
String dateStart = currWeekCalender.get(Calendar.YEAR) + "-" + addZero((currWeekCalender.get(Calendar.MONTH) + 1)) + "-" + addZero(currWeekCalender.getFirstDayOfWeek());
currWeekCalender.add(Calendar.DAY_OF_MONTH,7);
String dateEnd = currWeekCalender.get(Calendar.YEAR) + "-" + addZero((currWeekCalender.get(Calendar.MONTH) + 1)) + "-" + addZero(currWeekCalender.get(Calendar.DAY_OF_MONTH));
but the results are not correct, also I want previous weeks date.
Thanks

Hello to all coders :)
I work on little app to dive some data from database. To calculate previous weeks start and end date i use this code:
// Calendar object
Calendar cal = Calendar.getInstance();
// "move" cal to monday this week (i understand it this way)
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
// calculate monday week ago (moves cal 7 days back)
cal.add(Calendar.DATE, -7);
Date firstDateOfPreviousWeek = cal.getTime();
// calculate sunday last week (moves cal 6 days fwd)
cal.add(Calendar.DATE, 6);
Date lastDateOfPreviousWeek = cal.getTime();
Hope, that helps.

Your problem is that getFirstDayOfWeek() returns the first day of the week; e.g., Sunday in US, Monday in France. It does not return a day of the month. See javadoc.
The first day in a month that is the start of the week is (in pseudo-code)
((7 + (firstDayOfWeek - dayOfWeek(firstOfMonth))) % 7) + 1
You can translate that into java.util.Calendar code if you like, but I would suggest using Joda time instead.
also I want previous weeks date.
Just subtract seven days maybe using add
currCalendar.add(Calendar.DAY_OF_MONTH, -7)
This may involve underflow, but add deals with that.
add(f, delta)
adds delta to field f. This is equivalent to calling set(f, get(f) + delta) with two adjustments:
Add rule 1. The value of field f after the call minus the value of field f before the call is delta, modulo any overflow that has occurred in field f. Overflow occurs when a field value exceeds its range and, as a result, the next larger field is incremented or decremented and the field value is adjusted back into its range.

Java 8 version
This prints previous 10 weeks
final ZonedDateTime input = ZonedDateTime.now();
for(int i = 1; i < 10; i++) {
final ZonedDateTime startOfLastWeek = input.minusWeeks(i).with(DayOfWeek.MONDAY);
System.out.print(startOfLastWeek.format(DateTimeFormatter.ISO_LOCAL_DATE));
final ZonedDateTime endOfLastWeek = startOfLastWeek.plusDays(6);
System.out.println(" - " + endOfLastWeek.format(DateTimeFormatter.ISO_LOCAL_DATE));
}

Related

how does visual foxpro handle date calculation? (comming from java) result for date()-day(date())+1 operation?

what is the correct value for the formula date()-day(date())+1?
if date() returns '2016/5/5'
is it, 2016/5/1? or 2016/4/29?
because when converting code from visual foxpro to java?
following code produces different result.
Calendar today2 = Calendar.getInstance();
Calendar endDate = Calendar.getInstance();
endDate.add(Calendar.DATE, -1 * today2.get(Calendar.DATE));
endDate.add(Calendar.DATE, 1);
above code produces 2016/5/1, while:
Calendar today2 = Calendar.getInstance();
today2.add(Calendar.DATE, 1);
Calendar endDate = Calendar.getInstance();
endDate.add(Calendar.DATE, -1 * today2.get(Calendar.DATE));
above code produces 2016/4/29.
not sure which conversion is correct?
Actually it is obvious and 2016/5/1. Math is simple:
date() - day(date()) would be 2016/5/5 - 5 days which is 2016/4/30 (theDate - day(theDate) gives last day of previous month, adding 1 gives first day of month that theDate is in). Adding 1 day to it means 2016/5/1.
I don't know Java, but to me your 2nd Java code is wrong.
In first one, you are subtracting day of month and then adding 1 (same as what VFP is doing).
In second one, you are setting today2 to "tomorrow", then subtracting tomorrow's day of month from today's date. Which would mean date() - (day(date()+1)) and you would get the day before last month's end date.
Update: I think you can simplify your code as:
Calendar today = Calendar.getInstance();
today.add(Calendar.DATE, 1 - today2.get(Calendar.DATE));
IOW the VFP code to find start of a month:
firstDayOfMonth = theDate - day(theDate) + 1
should translate to:
Calendar firstDayOfMonth = Calendar.getInstance();
firstDayOfMonth.add(Calendar.DATE, 1 - firstDayOfMonth.get(Calendar.DATE));

Calendar field increment gives unexpected results

I'm working on creating a method to show the difference in time between two dates. To do this, I am using Calendar, and subtracting the dates to receive the remaining number available. However, for some reason, it's returning unexpected results. Here is my method in an extended Date class:
public String getReadableTimeDifference(Date fromDate, boolean showMilliseconds) {
String[] result = new String[7];
Calendar calendar = Calendar.getInstance();
Calendar from = Calendar.getInstance();
calendar.setTime(this);
from.setTime(fromDate);
// The two dates are correct. using a polymorphic method getReadableTimeDifference(boolean),
// it supplies this method with the current date. "this" is always a date in the future.
// Let's say that "this" is a date 10 seconds in the future:
System.out.println(from.getTime());
System.out.println(this);
// Since it's 10 seconds in the future, it will print the same (2016):
System.out.println(calendar.get(Calendar.YEAR) + " " + from.get(Calendar.YEAR));
// It should subtract the from date (2016) from the existing date (2016)
calendar.add(Calendar.YEAR, -from.get(Calendar.YEAR));
calendar.add(Calendar.MONTH, -from.get(Calendar.MONTH));
calendar.add(Calendar.DATE, -from.get(Calendar.DATE));
calendar.add(Calendar.HOUR, -from.get(Calendar.HOUR));
calendar.add(Calendar.MINUTE, -from.get(Calendar.MINUTE));
calendar.add(Calendar.SECOND, -from.get(Calendar.SECOND));
calendar.add(Calendar.MILLISECOND, -from.get(Calendar.MILLISECOND));
// It should print "0" (because 2016-2016 = 0) but instead it prints 2.
System.out.println(calendar.get(Calendar.YEAR));
int years = Math.abs(calendar.get(Calendar.YEAR));
int months = Math.abs(calendar.get(Calendar.MONTH));
int days = Math.abs(calendar.get(Calendar.DATE));
int hours = Math.abs(calendar.get(Calendar.HOUR));
int minutes = Math.abs(calendar.get(Calendar.MINUTE));
int seconds = Math.abs(calendar.get(Calendar.SECOND));
int milliseconds = Math.abs(calendar.get(Calendar.MILLISECOND));
if (years > 0) {
result[0] = Utilities.prettyNumerate("year", years);
}
if (months > 0) {
result[1] = Utilities.prettyNumerate("month", months);
}
if (days > 0) {
result[2] = Utilities.prettyNumerate("day", days);
}
if (hours > 0) {
result[3] = Utilities.prettyNumerate("hour", hours);
}
if (minutes > 0) {
result[4] = Utilities.prettyNumerate("minute", minutes);
}
if (seconds > 0) {
result[5] = Utilities.prettyNumerate("second", seconds);
}
if (milliseconds > 0 && showMilliseconds) {
result[6] = Utilities.prettyNumerate("millisecond", milliseconds);
}
return Utilities.join(Utilities.clean(result), ", ", " and ");
}
prettyNumerate takes a number and appends an "s" to the end of the supplied string if it's over 1, under -1 or 0. clean cleans an array of any null or empty elements. join join's an array by a delimiter, and a final delimiter for the last element. The expected outcome should be:
10 seconds
But instead it's:
2 years, 11 months, 31 days and 10 seconds
Nothing else is being manipulated within this custom date. When I instantiate this custom date, after any custom code is completed I print out this.getTime() and it prints out the correct time in milliseconds, which is 10 seconds into the future as it should be.
The year field in Calendar object of Java is relative to the era. By setting the year to something less or equal to 0 the calendar automatically corrects this by switching the era (from AD to BC or from BC to AD). This behaviour is better known from the other fields. For example, if you set the month to something negative, the year gets decremented accordingly.
Those corrections aren't made individually but rather they are made all at once, usually when you call getTime() to read out the resulting date.
Therefore, if you subtract year 2016 from a date in 2016, it automatically gets corrected to 1st century BC. When you do more subtractions, the time actually reaches 2nd century BC.
As suggested in some comments, you will be better off using Joda time for your usecase.

Why GregorianCalendar returns 0 instead of MONTH?

I have a problem with creating dates.
Calendar gc = new GregorianCalendar();
int leto = randBetween(2001, 2020);
gc.set(GregorianCalendar.YEAR, leto);
int dan= randBetween(1, gc.getActualMaximum(GregorianCalendar.DAY_OF_YEAR));
gc.set(GregorianCalendar.DAY_OF_YEAR, dan);
// System.out.println(gc.get(GregorianCalendar.YEAR) + "-" +
// gc.get(GregorianCalendar.MONTH) + "-" +
// gc.get(GregorianCalendar.DAY_OF_MONTH));
public static int randBetween(int start, int end) {
return start + (int)Math.round(Math.random() * (end - start));
}
I have a function for generating a date but in this function there are a lot of failures. I get many dates where the MONTH value is not set.
31,6,2004 1,7,2004
23,0,2013 24,0,2013
19,0,2008 20,0,2008
31,9,2014 31,9,2014
But I don't know why this happens?
This code is not ‘failing’, it is however not giving the expected result.
The dates that you are seeing are:
23,0,2013 -- 23rd of January, 2013.
31,6,2013 -- 31st of July, 2013.
That is, month is not 1-based, unlike day, it is 0-based.
Rest assured, this is fairly common mistake with the Java Date API, and probably the only person who thinks that is is logical is the person who came up with this API, and probably not even them anymore…

Android Calendar: Changing the start day of week

i have a little problem, i'm developing an application, and i need to change the start day of the week from monday to another one (thursday, of saturday). is this possible in android,
i need to calculate the start to week and its end knowing the date. (the week starts ano thursday as example)
Note: i'm just a beginner in android development.
here is my code
SimpleDateFormat dateformate = new SimpleDateFormat("dd/MM");
// get today and clear time of day
Calendar cal = Calendar.getInstance();
// get start of this week in milliseconds
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
cal.add(Calendar.DAY_OF_YEAR, 7*(WeekIndex-1));
result = dateformate.format(cal.getTime());
cal.add(Calendar.DAY_OF_YEAR, 6 );
result=result+" - " + dateformate.format(cal.getTime());
using the above code im getting the result but with monday as the star of week.
Note: i can't add day to the result because week index changes with the changing of it's start
Calendar days have values 1-7 for days Sunday-Saturday. getFirstDayOfWeek returns one of this values (usually of Monday or Sunday) depending on used Locale. Calendar.getInstance uses default Locale depening on phone's settings, which in your case has Monday as first day of the week.
One solution would be to use other Locale:
Calendar.getInstance(Locale.US).getFirstDayOfWeek()
would return 1, which is value of Calendar.SUNDAY
Other solution would be to use chosen day of week value like
cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
Problem is, Calendar is using its inner first day of the week value in set as well. Example:
Calendar mondayFirst = Calendar.getInstance(Locale.GERMANY); //Locale that has Monday as first day of week
mondayFirst.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
log(DateUtils.formatDateTime(context, mondayFirst.getTimeInMillis(), 0));
//prints "May 19" when runned on May 13
Calendar sundayFirst = Calendar.getInstance(Locale.US); //Locale that has Sunday as first day of week
sundayFirst.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
log(DateUtils.formatDateTime(context, sundayFirst.getTimeInMillis(), 0));
//prints "May 12" when runned on May 13
If you don't want to use Locale or you need other day as the first day of the week, it may be best to calculate start of the week on your own.
GregorianCalendar cal = new GregorianCalendar(yy, currentMonth, 0);
changing the value 0 - starts day from monday
changing the value 1 - starts day from sunday
and so on..
hope this helps and works :)
public int getWeekdayOfMonth(int year, int month){
Calendar cal = Calendar.getInstance();
cal.set(year, month-1, 1);
dayOfWeek = cal.get(Calendar.DAY_OF_WEEK)-1;
return dayOfWeek;
}
weekday = getWeekdayOfMonth();
int day = (weekday - firstweek) < 0 ? (7 - (firstweek - weekday)) : (weekday - firstweek);
"firstweek" means what the start day of you want
then you can calculate the first day you should show.If you have simple method,please tell us. thks
Problem in my case was using Calendar instance returned by MaterialDialog DatePicker, which although having the same Locale as my Calendar.getInstance(Locale...), was having different Calendar.firstDayOfWeek. If you're experiencing the same issue, my workaround was to create new instance of Calendar with my Locale and just changing the property time to the one returned by the DatePicker as following:
val correctCal = Calendar.getInstance(Locale...)?.apply {
time = datePickerCal.time
}
This should return proper Calendar.firstDayOfWeek based on your Locale.

Timetable implementation in Java?

I need a Timetable class that would work like (a rough example to explain the idea):
Timetable timetable = new Timetable("Mon-Fri 8:00-17:00");
Date eta = timetable.increment(new Date(), 3, Calendar.HOURS);
eta should be the point in time, which is exactly 3 hours ahead of current time, but only the time between 8:00 and 17:00 is taken into account. This may sound like an interview question, but I need such a class for a business purpose and I suspect that some open source implementation exists already.
I think this is very close to parse the string into a date then use java.util.Calendar to either add or subtract the date.
check this
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html#add(int, int)
// create a calendar
Calendar cal = Calendar.getInstance()
// print current date
System.out.println("The current date is : " + cal.getTime());
// add 20 days to the calendar
cal.add(Calendar.DATE, 20);
System.out.println("20 days later: " + cal.getTime());
// subtract 2 months from the calendar
cal.add(Calendar.MONTH, -2);
System.out.println("2 months ago: " + cal.getTime());
// subtract 5 year from the calendar
cal.add(Calendar.YEAR, -5);
System.out.println("5 years ago: " + cal.getTime());

Categories