Related
I tried to write a code which displays the days of the week for the last 10 dates.
Here's a part of the code:
Calendar cal = Calendar.getInstance();
for(int i=0; i<=9;i++) {
cal.add(Calendar.DATE, -i);
Date tday=cal.getTime();
SimpleDateFormat dy = new SimpleDateFormat("EEE");
String d9 = dy.format(tday);
System.out.println(d9);
}
Instead of showing all the last 10 days in an order it is displaying like this:
Thu
Wed
Mon
Fri
Mon
Wed
Thu
Thu
Wed
Mon
Fri
Where did I make the mistake?
try this.
boolean work = true;
int day = 0; // 0 = today, 1 = yesterday etc...
int subDay = 0; // subtract day
while (work){
Calendar cal = Calendar.getInstance(); // get current time
cal.add(Calendar.DAY_OF_WEEK, subDay); // subtract day
// working days are Mon, Tue, Wed, Thu, Fri. If we get saturdays or sundays, we want to skip that days,
// so we use if declaration
if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
subDay--;
continue;
}
Date tday=cal.getTime();
SimpleDateFormat dy = new SimpleDateFormat("EEE");
String d9 = dy.format(tday);
System.out.println("Day: " + day + " - " + d9);
day ++;
subDay--;
if (day >= 10){work=false;} // here we declara how much day we want to go back, and we break loop.
}
Avoid j.u.Date
The first mistake was using the java.util.Date and .Calendar classes bundled with Java. They are notoriously troublesome. Avoid them.
Use a decent date-time library. In Java that means either:
Joda-Time
java.time package in Java 8 (inspired by Joda-Time)
Both have their pros and cons.
Both offer a LocalDate class, which you need to represent a date-only without any time-of-day portion.
Date-Time Versus Text
The Question’s code mixes date-time values with their String representations. Better to get your work done using date-time values. Afterwards, separately, create String representations for presentation to the user. The idea is a separation of concerns, to make your code more clear and easier to test/debug.
Joda-Time
Example code in Java-Time.
You will have to specify which days of the week are business days.
Note the use of a time zone. The current date depends on your position on the globe (the time zone). A new day dawns in Paris earlier than in Montréal. If you omit the time zone, the JVM’s default is applied. Better to specify, even by calling getDefault(), than to rely on an implicit default.
First we gather a collection of desired date-time values.
int requiredCountOfDays = 10; // The Question demands 10 previous working days.
List<LocalDate> days = new ArrayList<LocalDate>( requiredCountOfDays ); // Collect desired LocalDate objects.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" ); // Specify time zone by which to get current date.
LocalDate today = LocalDate.now( timeZone ); // Get the current date at this moment in specified time zone.
LocalDate localDate = today; // Define var to decrement for previous days.
while ( days.size() < requiredCountOfDays ) { // Loop until we fill the list (10 elements).
localDate = localDate.minusDays( 1 ); // Decrement to get previous day.
// Hard-code what days are business days vs weekend days.
boolean isWeekend = ( ( localDate.getDayOfWeek() == DateTimeConstants.SATURDAY ) || ( localDate.getDayOfWeek() == DateTimeConstants.SUNDAY ) ); // Hard-coding for weekend because it is easier to type than coding for the more numerous week days.
if ( !isWeekend ) { // If business day…
days.add( localDate ); // …collect this day.
}
}
Afterwards, we present those values in a localized String format.
List<String> daysOfWeek = new ArrayList<String>( days.size() ); // Collect the same number of LocalDate objects, rendered as Strings.
DateTimeFormatter formatter = DateTimeFormat.forPattern( "EEE" ); // Generate name of day-of-week, abbreviated.
for ( LocalDate day : days ) {
String dayOfWeek = formatter.print( day ); // Generate String representation.
daysOfWeek.add( dayOfWeek ); // Collect the string.
}
Dump to console…
System.out.println( "days: " + days );
System.out.println( "daysOfWeek: " + daysOfWeek );
When run…
days: [2014-06-18, 2014-06-17, 2014-06-16, 2014-06-13, 2014-06-12, 2014-06-11, 2014-06-10, 2014-06-09, 2014-06-06, 2014-06-05]
daysOfWeek: [Wed, Tue, Mon, Fri, Thu, Wed, Tue, Mon, Fri, Thu]
I'm trying to calculate the difference between two days in amount of days. For some reason comparing 01-03-2013 and 01-04-2013 gives the result 30, as does comparing 01-03-2013 and 31-03-2013
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(2013, Calendar.MARCH, 1);
Date start = cal.getTime();
cal.set(2013, Calendar.APRIL, 1);
Date end = cal.getTime();
long days = TimeUnit.MILLISECONDS.toDays(end.getTime() - start.getTime());
System.out.println("!!! Amount of days : " + String.valueOf(days));
>> 30
cal.set(2013, Calendar.MARCH, 1);
start = cal.getTime();
cal.set(2013, Calendar.MARCH, 31);
end = cal.getTime();
days = TimeUnit.MILLISECONDS.toDays(end.getTime() - start.getTime());
System.out.println("!!! Amount of days : " + String.valueOf(days));
>> 30
Why is this?
You will get those results if daylight savings started in your time zone on 31 March.
Between 1 March and 1 April, you have 30 24-hour days and one 23-hour day, because of the start of daylight savings. If you divide the total number of milliseconds by 24 x 60 x 60 x 1000, then you will get 30 plus 23/24. This gets rounded down to 30.
Time Zone
The correct answer by David Wallace explains that Daylight Saving Time or other anomalies affects the results of your code. Relying on default time zones (or outright ignoring time zones) will get you into this kind of trouble.
Make Span Inclusive-Exclusive
Also, the proper way to define a span of time is to make the beginning inclusive and the ending exclusive. So if you want the month of March, you need to go from first moment of first day to first moment of first day after March (April 1).
For lengthy discussion of this idea, see my other answers such as this one and this one.
Here's a diagram of mine lifted from other answers:
Joda-Time
The java.util.Date/Calendar classes bundled with Java are notoriously troublesome. Avoid them. Use either Joda-Time, or in Java 8, the new java.time.* package (inspired by Joda-Time).
The Joda-Time 2.3 library provides classes dedicated to spans of time: Period, Duration, and Interval. That library also has some handy static utility methods, such as Days.daysBetween.
Joda-Time's DateTime objects do know their own time zone, unlike java.util.Date/Calendar which seem to have a time zone but do not.
// Specify a timezone rather than rely on default.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime marchFirst = new DateTime( 2013, DateTimeConstants.MARCH, 1, 0, 0, 0, timeZone );
DateTime aprilFirst = new DateTime( 2013, DateTimeConstants.APRIL, 1, 0, 0, 0, timeZone );
int days = Days.daysBetween( marchFirst, aprilFirst).getDays();
Dump to console…
System.out.println( "marchFirst: " + marchFirst );
System.out.println( "aprilFirst: " + aprilFirst ); // Note the change in time zone offset in the output.
System.out.println( "days: " + days );
When run, notice:
The correct answer: 31
The difference in time zone offset because of Daylight Saving Time in France.
marchFirst: 2013-03-01T00:00:00.000+01:00
aprilFirst: 2013-04-01T00:00:00.000+02:00
days: 31
When I run this version of your code here in United States west coast time zone:
java.util.Calendar cal = java.util.Calendar.getInstance();
cal.clear();
cal.set( 2013, java.util.Calendar.MARCH, 1 );
java.util.Date start = cal.getTime();
cal.set( 2013, java.util.Calendar.APRIL, 1 );
java.util.Date end = cal.getTime();
long days = java.util.concurrent.TimeUnit.MILLISECONDS.toDays( end.getTime() - start.getTime() );
System.out.println( "!!! Amount of days : " + String.valueOf( days ) );
cal.set( 2013, java.util.Calendar.MARCH, 1 );
start = cal.getTime();
cal.set( 2013, java.util.Calendar.MARCH, 31 );
end = cal.getTime();
days = java.util.concurrent.TimeUnit.MILLISECONDS.toDays( end.getTime() - start.getTime() );
System.out.println( "!!! Amount of days : " + String.valueOf( days ) );
I get:
!!! Amount of days : 30
!!! Amount of days : 29
For explanation, see comment by David Wallace on this answer.
Daylight Saving Time (United States) 2013 began at 2:00 AM on Sunday, March 10.
I executed same code in my system it is giving me output as :
!!! Amount of days : 31
please check your code again.
I'm trying to learn about Date objects and the DateFormat class and I keep getting an error in the examples I'm trying to do. The goal is to get a due date by adding 30 days to a pretend invoice date, and then to format that due date. The dueDate method, I believe, is correct, but I'm having trouble formatting it properly.
Here is the first thing I have that takes the invoice date and adds 30 days to it.
public Date getDueDate()
{
Calendar cal = new GregorianCalendar();
cal.setTime(getInvoiceDate());
cal.add(Calendar.DATE, 30);
Date dueDate = cal.getTime();
return dueDate;
}
The next part is where I'm having the trouble, as it keeps telling me it expects a Date object but is receiving a String and I'm not sure why, as I'm supplying a Date object.
public Date getFormattedDueDate()
{
Date dueDate = getDueDate();
DateFormat shortDate = DateFormat.getDateInstance(DateFormat.SHORT);
return shortDate.format(dueDate);
}
Can anyone help me figure out why it's telling me that my supplied variable (dueDate) is a String when it's coded as a Date object?
format(Date date) Formats a Date into a date/time String.
Shamse is right
shortDate.format(dueDate);
returns a String, you can easly fix this changing your return type
public String getFormattedDueDate()
{
Date dueDate = getDueDate();
DateFormat shortDate = DateFormat.getDateInstance(DateFormat.SHORT);
return shortDate.format(dueDate);
}
The answer by Shamse is correct.
For the heck of it, here's the same kind of code but:
Written using the third-party library, Joda-Time 2.3
Care taken with time zones. Depending on default time zones is risky.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
java.util.Date date = new Date(); // = getInvoiceDate();
org.joda.time.DateTime invoiceStoredDateTime = new org.joda.time.DateTime( date );
// Set to desired time zone. Ideally that invoice date was stored in UTC.
// Time Zone list: http://joda-time.sourceforge.net/timezones.html
org.joda.time.DateTimeZone denverTimeZone = org.joda.time.DateTimeZone.forID( "America/Denver" );
org.joda.time.DateTime invoiceZonedDateTime = invoiceStoredDateTime.toDateTime( denverTimeZone );
// Call method .withTimeAtStartOfDay() to set the time component to first moment of the day.
org.joda.time.DateTime dueDateInThirtyDays = invoiceZonedDateTime.plusDays( 30 ).withTimeAtStartOfDay();
org.joda.time.DateTime dueDateInOneMonth = invoiceZonedDateTime.plusMonths( 1 ).withTimeAtStartOfDay(); // Smart month calculation, aiming at same day number of month.
// Style – Specify a character of 'S' for short style, 'M' for medium, 'L' for long, and 'F' for full. First for date, second for time.
// A date or time may be omitted by specifying a style character '-'.
String dueDateAsString = org.joda.time.format.DateTimeFormat.forStyle("S-").withLocale( Locale.US ).print( dueDateInThirtyDays );
org.joda.time.DateTime dueDateInUtcForStorage = dueDateInThirtyDays.toDateTime( org.joda.time.DateTimeZone.UTC );
Show values on the console:
System.out.println( "date: " + date );
System.out.println( "invoiceZonedDateTime: " + invoiceZonedDateTime );
System.out.println( "dueDateInThirtyDays: " + dueDateInThirtyDays );
System.out.println( "dueDateInOneMonth: " + dueDateInOneMonth );
System.out.println( "dueDateAsString: " + dueDateAsString );
System.out.println( "dueDateInUtcForStorage: " + dueDateInUtcForStorage );
When run…
date: Thu Nov 28 13:39:05 PST 2013
invoiceZonedDateTime: 2013-11-28T14:39:05.125-07:00
dueDateInThirtyDays: 2013-12-28T00:00:00.000-07:00
dueDateInOneMonth: 2013-12-28T00:00:00.000-07:00
dueDateAsString: 12/28/13
dueDateInUtcForStorage: 2013-12-28T07:00:00.000Z
I follow this question: Convert from java.util.date to JodaTime
I have date: Sun Jan 01 00:00:00 CET 1854
now I want to convert it to joda datetime:
DateTime dateTime = new DateTime(date);
and now when I print this date I got:
1853-12-31T23:57:44.000+00:57:44
what is wrong and why my date changed ? How I can get the same date ?
UPDATE:
I get date using calendar:
Calendar cal1 = Calendar.getInstance();
cal1.set(1854, 0, 1, 0, 0, 0);
cal1.getTime()
UPDATE2:
propably there is problem with milseconds:
Calendar cal1 = Calendar.getInstance();
cal1.set(1854, 0, 1, 0, 0, 0);
DateTime start = new DateTime(1854, 1, 1, 0, 0, 0);
System.out.println(start.getMillis());
System.out.println(cal1.getTime().getTime());
because this code return:
-3660598664000
-3660598799438
but I dont know why
UPDATE3:
Joda-Time uses the accurate time-zone database, which has Local Mean Time (LMT) for years before time-zones started. To quote Wikipedia:
Local mean time is a form of solar time that corrects the variations of local apparent time, forming a uniform time scale at a specific longitude.
The JDK doesn't use LMT, thus the times differ.
ok I solve it. Is isnt nice but it works what is important
Calendar calendar = Calendar.getInstance();
calendar.setTime(datum);
DateTime current = new DateTime(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1,
calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
IF you have the date as type of java.util.date you can use
java.util.Date date = ....
DateTime dateTime = new DateTime(date.getTime());
this code
Calendar cal1 = Calendar.getInstance();
cal1.set(1854, 0, 1, 0, 0, 0);
DateTime start = new DateTime(cal1.getTime());
System.out.println(start);
System.out.println(cal1.getTime());
outputs :
1854-01-01T00:00:00.941Z
Sun Jan 01 00:00:00 GMT 1854
I imagine the millisecond discrepancy is calendar choosign the saem time of day as now, to start the milliseconds count on. Whereas joda-time chooses midnight. Or something similarly obtuse. I try and stay away from java's built in Calendar and Date, they are an abomination.
The Answer by JodaStephen is correct and should be accepted.
The Joda-Time team have instructed us to migrate to the java.time framework built into Java 8 and later. So I was curious to try this problem in java.time and compare results.
The Question says the input data is for CET offset-from-UTC, but the code in the Question ignores that fact. My code below uses an offset of one hour ahead of UTC to account for CET.
java.time
The CET means one hour ahead of UTC. Since we have only an offset-from-UTC and not a full time zone, I use the OffsetDateTime class, for +01:00.
LocalDateTime localDateTime = LocalDateTime.of ( 1854 , 1 , 1 , 0 , 0 , 0 , 0 ); // The nineteenth century.
ZoneOffset offset = ZoneOffset.of ( "+01:00" ); // “CET” means one hour ahead of UTC.
OffsetDateTime odt = OffsetDateTime.of ( localDateTime , offset );
Instant instant = odt.toInstant (); // A moment on the timeline in UTC, with resolution in nanoseconds.
long m = instant.toEpochMilli ();
System.out.println ( "odt: " + odt + " | millis: " + m );
odt: 1854-01-01T00:00+01:00 | millis: -3660598800000
Joda-Time
Same code, but using Joda-Time 2.9.3.
DateTimeZone zone = DateTimeZone.forOffsetHoursMinutes ( 1 , 0 );
DateTime dateTime = new DateTime ( 1854 , 1 , 1 , 0 , 0 , zone );
long millis = dateTime.getMillis ();
System.out.println ( "dateTime: " + dateTime + " | millis: " + millis );
dateTime: 1854-01-01T00:00:00.000+01:00 | millis: -3660598800000
Result is same as java.time.
java.util.Calendar
For comparison only. Normally you should avoid the old java.util.Date/.Calendar classes as they have proven to be poorly designed, confusing, and troublesome.
Calendar calendar = Calendar.getInstance ();
calendar.set ( 1854 , 0 , 1 , 0 , 0 , 0 );
TimeZone zone = TimeZone.getTimeZone ( "GMT+01:00" );
calendar.setTimeZone ( zone );
long millis = calendar.getTimeInMillis ();
System.out.println ( "calendar: " + calendar + " | millis: " + millis );
calendar: java.util.GregorianCalendar[time=-3660598799715,areFieldsSet=true,areAllFieldsSet=false,lenient=true,zone=sun.util.calendar.ZoneInfo[id="GMT+01:00",offset=3600000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=1854,MONTH=0,WEEK_OF_YEAR=1,WEEK_OF_MONTH=1,DAY_OF_MONTH=1,DAY_OF_YEAR=1,DAY_OF_WEEK=1,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=285,ZONE_OFFSET=3600000,DST_OFFSET=0] | millis: -3660598799715
Different results. Here we have -3660598799715 versus -3660598800000 in java.time & Joda-Time, a difference of 285.
Europe/Brussels
I also tried all three with a time zone of Europe/Brussels rather than an offset-from-UTC.
In java.time. Using ZonedDateTime class rather than OffsetDateTime.
LocalDateTime localDateTime = LocalDateTime.of ( 1854 , 1 , 1 , 0 , 0 , 0 , 0 ); // The nineteenth century.
ZoneId zoneId = ZoneId.of ( "Europe/Brussels" );
ZonedDateTime zdt = ZonedDateTime.of ( localDateTime , zoneId );
Instant instant = zdt.toInstant (); // A moment on the timeline in UTC, with resolution in nanoseconds.
long m = instant.toEpochMilli ();
System.out.println ( "zdt: " + zdt + " | millis: " + m );
zdt: 1854-01-01T00:00+00:17:30[Europe/Brussels] | millis: -3660596250000
In Joda-Time. Only first line is different.
DateTimeZone zone = DateTimeZone.forID ( "Europe/Brussels" );
dateTime: 1854-01-01T00:00:00.000+00:17:30 | millis: -3660596250000
In java.util.Calendar. Some code except for the TimeZone line:
TimeZone zone = TimeZone.getTimeZone ( "Europe/Brussels" );
calendar: java.util.GregorianCalendar[time=-3660598799151,areFieldsSet=true,areAllFieldsSet=false,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Europe/Brussels",offset=3600000,dstSavings=3600000,useDaylight=true,transitions=184,lastRule=java.util.SimpleTimeZone[id=Europe/Brussels,offset=3600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=1854,MONTH=0,WEEK_OF_YEAR=1,WEEK_OF_MONTH=1,DAY_OF_MONTH=1,DAY_OF_YEAR=1,DAY_OF_WEEK=1,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=849,ZONE_OFFSET=3600000,DST_OFFSET=0] | millis: -3660598799151
All three using Europe/Brussels differ from their version with offset of +01:00.
And again java.time & Joda-Time agree with each other (-3660596250000), while differing from Calendar (-3660598799151), a difference of 2,549,151 (about 42 and a half minutes).
I am seriously looking for this code...I am new programmer.
Actually I want to make all dates with flag, which all are sunday in a particular year.
Please, I am eagerly waiting for your response....
Create a new calendar. Set the time to 1/1/yyyy and some time. Check if the current date is a Sunday and roll forward one day until it is. That's the first Sunday of the year. Roll forward 7 days until the year no longer matches, marking as you go.
Study the the docs of java.util.Calendar carefully.
If i was doing it I would use Joda Time to find the first Sunday in the year using LocalDate. Create 1st of Jan and then add 1 day until it is a Sunday, then add 7 days until your run out of year.
LocalDate date = new LocalDate(YEAR, 1, 1);
while ( date.dayOfWeek() != 7 )
{
date = date.addDays(1);
}
while ( date.year() == YEAR )
{
date = date.addDays(7);
}
Or something like that.
Something like this should work.
int year = 2009;
Calendar cal = new GregorianCalendar(year, Calendar.JANUARY, 1);
for (int i = 0, inc = 1; i < 366 && cal.get(Calendar.YEAR) == year; i+=inc) {
if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
// this is a sunday
cal.add(Calendar.DAY_OF_MONTH, 7);
inc = 7;
} else {
cal.add(Calendar.DAY_OF_MONTH, 1);
}
}
This is an example code using java.util.Calendar and java.util.GregorianCalendar that prints out each Sunday of the year 2009.
A lot of optimizing can be done in formatting the date, but i'll leave that as an exercise for you.
import java.util.Calendar;
import java.util.GregorianCalendar;
public class Test
{
public static void main(String[] args)
{
int year =2009;
int dayOfWeek = Calendar.SUNDAY;
String dayOfWeekString = "Sunday";
// instantiate Calender and set to first Sunday of 2009
Calendar cal = new GregorianCalendar();
cal.set(2009, 0, 1, 0, 0); cal.getTime();
cal.set(Calendar.DAY_OF_WEEK, dayOfWeek); cal.getTime();
int i = 1;
while (cal.get(Calendar.YEAR) == 2009)
{
System.out.println(dayOfWeekString + " " + i + ": " + cal);
cal.add(Calendar.DAY_OF_MONTH, 7);
i++;
}
}
}
As you can see, TiGz's way of using Joda Time is a lot simpler.
List arrList = new ArrayList();
SimpleDateFormat format1 = new SimpleDateFormat("dd-M-yyyy");
Date date = null;
Calendar cal = Calendar.getInstance();
for (int i = 0; i <= 51; i++)
{
try
{
cal.add(Calendar.WEEK_OF_YEAR, +1);
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
String formatted = format1.format(cal.getTime());
date = format1.parse(formatted);
arrList.add(date);
} catch (Exception e) {
e.printStackTrace();
}
}
java.time
Java 8 and later comes with the new java.time package. Inspired by Joda-Time, defined by JSR 310, extended by the ThreeTen-Extra project. These new classes supplant the notoriously troublesome java.util.Date/.Calendar & java.text.SimpleDateFormat and such.
Note that we specify a time zone, crucial for determining a date. For example, a new day dawns earlier in Paris than in Montréal.
ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Time zone is crucial in determining the date. A new day dawns earlier in Paris than In Montréal, for example.
You would write this code to use only LocalDate without any time-of-day. But in business, the full date-time is often more useful. So my example here uses ZonedDateTime.
To be neat, I want the time-of-day set to first moment of the day. You might assume that means 00:00:00.0 but not always because of anomalies such as Daylight Saving Time. To soft-code this first-moment, we want to call the atStartOfDay method found on LocalDate. So we start with LocalDate, then use that method to get a ZonedDateTime object.
Again, note that we specify a time zone when getting today’s date. A very common mistake is to omit time zone. When omitted, the JVM’s current default time zone will be implicitly applied. That means your results can vary by machine or by admin’s settings. Even worse, any code in any thread of any app within this JVM can make a call to change that default time zone at any moment during runtime while your app executes! So always specify rather than rely implicitly on current default.
LocalDate today = LocalDate.now( zoneId ); // We want a ZonedDateTime, but starting with a LocalDate in order to get first moment of the day (see next line).
ZonedDateTime todayStart = today.atStartOfDay( zoneId ); // Set time-of-day to first moment of this date, just to be neat. Usually that time is '00:00:00.0' but not always.
The java.time framework includes some handy TemporalAdjustors to get first day of year, and from there, the first Sunday of that month.
ZonedDateTime firstOfThisYear = todayStart.with( TemporalAdjusters.firstDayOfYear( ) );
ZonedDateTime zdtFirstOfNextYear = firstOfThisYear.with( TemporalAdjusters.firstDayOfNextYear( ) );
ZonedDateTime firstSundayOfThisYear = firstOfThisYear.with( TemporalAdjusters.dayOfWeekInMonth( 1, DayOfWeek.SUNDAY ) );
Now we are set to loop through all the weeks of the year. We increment a week at a time until we find ourselves in the next year. We collect each Sunday in a List.
ZonedDateTime zdt = firstSundayOfThisYear; // Var changing throughout loop.
List< ZonedDateTime > sundays = new ArrayList<>( 53 ); // Set initial capacity to maximum number of values.
while ( zdt.isBefore( zdtFirstOfNextYear ) ) {
// Handle this iteration.
sundays.add( zdt );
System.out.println( "Sunday # " + sundays.size( ) + " : " + zdt );
// Prepare next iteration.
zdt = zdt.plusWeeks( 1 );
}
When run.
Sunday # 1 : 2015-01-04T00:00-05:00[America/Montreal]
Sunday # 2 : 2015-01-11T00:00-05:00[America/Montreal]
…
Sunday # 51 : 2015-12-20T00:00-05:00[America/Montreal]
Sunday # 52 : 2015-12-27T00:00-05:00[America/Montreal]
A year has approximately 365 days, so the Big-O's n is pretty manageable. I'd say just iterate from the beginning of the year through to the last day of the year, and check if each day is a Sunday or not.
You need at least Calendar.get(), Calendar.DAY_OF_WEEK and Calendar.SUNDAY
I recently developed [Lamma Date] which is designed to serve this type of use cases.
Following code will print out all Sundays in 2014:
List<Date> sundays2014 = Dates.from(2014, 1, 1).to(2014, 12, 31).byWeek().on(DayOfWeek.SUNDAY).build();
for(Date date: sundays2014) {
System.out.println(date);
}
**this will give u all Sundays of the year **
invented By me and friend Hemant
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class Test {
public static void main(String[] args) {
SimpleDateFormat format =new SimpleDateFormat("dd-MMM-yyyy");
String DATE_FORMAT = "yyyy MM dd";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
Calendar c1 = Calendar.getInstance(); // today
String y=sdf.format(c1.getTime());
String years=y.substring(0,4);
int year=Integer.parseInt(years);
//Connection con=null;
Calendar cal = new GregorianCalendar(year, Calendar.JANUARY, 1);
for (int i = 0, inc = 1; i <366 && cal.get(Calendar.YEAR) == year; i+=inc) {
if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
// this is a sunday
String frm="";
frm=format.format(cal.getTime());
//System.out.println("From :"+frm);
System.out.println("the value of the sunday is "+format.format(cal.getTime()));
cal.add(Calendar.DAY_OF_MONTH, 7);
} else {
cal.add(Calendar.DAY_OF_MONTH, 1);
}
}
}
}