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
Related
I have specific date and i want to find last day number(integer) of month. I am using following code but always return current of date.
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = (Date) sdf.parse(year+"-"+(month<10?("0"+month):month)+"-01");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.DATE, -1);
Date dt = (Date) calendar.getTime(); -> dt is return current date always
example: my date = 2018/04/30 and i want to find 30.
I couldnt find answer at site.
Thnx
If using Java 8 (or higher), don't use Calendar. If using Java 6 or 7, you might want to consider using the ThreeTen Backport. In either case, use the Java Time API.
Using Java Time
Since input is int year and int month, use YearMonth.
To find last day number of month, call lengthOfMonth().
To get the date at the end of month, call atEndOfMonth().
Demo
int year = 2020;
int month = 2;
int lastDay = YearMonth.of(year, month).lengthOfMonth();
System.out.println(lastDay);
LocalDate date = YearMonth.of(year, month).atEndOfMonth();
System.out.println(date);
Output
29
2020-02-29
Using Joda-Time
If you don't have Java 8, and already use Joda-Time, do it this way:
Demo
int year = 2020;
int month = 2;
int lastDay = new LocalDate(year, month, 1).dayOfMonth().getMaximumValue();
System.out.println(lastDay);
LocalDate date = new LocalDate(year, month, 1).dayOfMonth().withMaximumValue();
System.out.println(date);
Output
29
2020-02-29
Using Calendar
If you insist on using Calendar, call getActualMaximum(Calendar.DAY_OF_MONTH) as also mentioned in other answers.
Since input is int year and int month, don't build and parse a string, just set Calendar fields directly. Note that "month" in Calendar is zero-based.
Demo
int year = 2020;
int month = 2;
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(year, month - 1, 1);
int lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
calendar.set(Calendar.DAY_OF_MONTH, lastDay);
Date date = calendar.getTime();
System.out.println(lastDay);
System.out.printf("%tF%n", date);
Output
29
2020-02-29
have specific date and i want to find last day number(integer) of month
getActualMaximum() is what you are looking for here.
Calendar cal = Calendar.getInstance();
cal.setTime(parsedDate);
cal.getActualMaximum(Calendar.DAY_OF_MONTH);
Calendar calendar =Calendar.getInstance();
calendar.set(Calendar.DATE, 1);
calendar.roll(Calendar.DATE, -1);
int lastDate=calendar.get(Calendar.DATE);
You can use calendar for that, like this:
calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
Or, if you have joda, which is usually better:
DateTime d = new DateTame(dt);
d.dayOfMonth().getMaximumValue();
First, how are you getting the year to be used?
it should be simple by using Java Time LocalDate:
import java.time.*;
import static java.time.Month.*;
import static java.time.temporal.TemporalAdjusters.*;
import static java.time.temporal.ChronoField.*;
int lastDay = LocalDate.now() // or whatever date you want
.with(Month.of(yourMonth))
.with(lastDayOfMonth())
.get(DAY_OF_MONTH);
// or, if you have year and month, and want to find the corresponding last day
int lastDay = LocalDate.of(yourYear, yourMonth, 1)
.with(lastDayOfMonth())
.get(DAY_OF_MONTH);
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);
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
Following is the code that I am using to calculate the week start date and end date for the given month.
Assume week start day is MONDAY and week end day is SUNDAY.
For example, JANUARY, 2013 will have 5 weeks.
If the month starts with Sunday - ignore that day
January 2013
first week - 31-Dec-2012 to 06-Jan-2013
second week - 07-jan-2013 to 13-jan-2013
Third week - 14-jan-2013 to 20-jan-2013
fourth week - 21-jan-2013 to 27-jan-2013
fifth week - 28-jan-2013 to 03-Feb-2013
public static void main(String[] args) {
List<List<String>> weekdates = getNumberOfWeeks(2013, Calendar.JULY);
for(List<String> weekDatesLoop:weekdates){
System.out.println("Start day: "+weekDatesLoop.get(0).toString());
System.out.println("End day: "+weekDatesLoop.get(1).toString());
}
}
public static List<List<String>> getNumberOfWeeks(int year, int month) {
System.out.println("Month Id: "+month);
month = month-1;
System.out.println("Month Id: " + month);
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
List<List<String>> weekdates = new ArrayList<List<String>>();
List<String> dates = new ArrayList<String>();
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, 1);
dates.add(format.format(c.getTime()));
//int numOfWeeksInMonth = 1;
while (c.get(Calendar.MONTH) == month) {
//System.out.println(c.get(Calendar.DAY_OF_WEEK) );
if (c.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
dates.add(format.format(c.getTime()));
weekdates.add(dates);
}
else if (c.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
dates = new ArrayList<String>();
dates.add(format.format(c.getTime()));
//numOfWeeksInMonth++;
}
c.add(Calendar.DAY_OF_MONTH, 1);
}
if(dates.size() < 2){
c.add(Calendar.DAY_OF_MONTH, -1);
dates.add(format.format(c.getTime()));
weekdates.add(dates);
}
System.out.println(weekdates);
return weekdates;
}
I am still working on this.
Can anyone please help me in fixing this?
You are using terrible date-time classes that were supplanted years ago by the modern java.time classes defined in JSR 310. This work is much easier now.
YearMonth
The YearMonth class represents a specific month as a whole. Specify the month using the Month enum.
YearMonth ym = YearMonth.of( 2013 , Month.JANUARY ) ;
LocalDate
Get the first of the month.
LocalDate firstOfMonth = ym.atDay( 1 ) ;
TemporalAdjuster
Get the previous Monday, or stay with this date if it is a Monday.
TemporalAdjuster ta = TemporalAdjusters.previousOrSame( DayOfWeek.MONDAY ) ;
LocalDate previousOrSameMonday = firstOfMonth.with( ta ) ;
Then loop a week at a time.
LocalDate endOfMonth = ym.atEndOfMonth() ;
LocalDate weekStart = previousOrSameMonday ;
do {
LocalDate weekStop = weekStart.plusDays( 6 ) ;
System.out.println( "Week: " + weekStart + " to " + weekStop ) ;
// Set up the next loop.
weekStart = weekStart.plusWeeks( 1 ) ;
} while ( ! weekStart.isAfter( endOfMonth ) ) ;
See this code run live at IdeOne.com.
Week: Monday, December 31, 2012 to Sunday, January 6, 2013
Week: Monday, January 7, 2013 to Sunday, January 13, 2013
Week: Monday, January 14, 2013 to Sunday, January 20, 2013
Week: Monday, January 21, 2013 to Sunday, January 27, 2013
Week: Monday, January 28, 2013 to Sunday, February 3, 2013
By the way, you might want to learn about, and consider using, the ISO 860 standard definition of a week. And then use the YearWeek class of the ThreeTen-Extra library.
A possible solution may be to not reinvent the wheel and use JodaTime or a similar library. For instance, you can use the dayOfWeek() function on a DateTime to get the information you're after.
I get the answer with the following code
List<List<String>> getNumberOfWeeks(int year, int month) {
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
List<List<String>> weekdates = new ArrayList<List<String>>();
List<String> dates;
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, 1);
while (c.get(Calendar.MONTH) == month) {
dates = new ArrayList<String>();
while (c.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
c.add(Calendar.DAY_OF_MONTH, -1);
}
dates.add(format.format(c.getTime()));
c.add(Calendar.DAY_OF_MONTH, 6);
dates.add(format.format(c.getTime()));
weekdates.add(dates);
c.add(Calendar.DAY_OF_MONTH, 1);
}
System.out.println(weekdates);
return weekdates;
}
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);