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]
Related
I want to check if my Date value from -
Date d = convertCurrentTimeToSpecificTimeZone("America/Chicago", 2, 30);
falls in the range of 10am to 6 pm.
I found some similar links on StackOverflow similar question and used some of the code from this thread.
All I want to check if the current time from any timezone falls under the range of 10 am to 6 pm. If Yes, print "yes" else print "no".
Currently for below code:
String string1 = "10:11:13";
Date time1 = new SimpleDateFormat("HH:mm:ss").parse(string1);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);
calendar1.add(Calendar.DATE, 1);
System.out.println(calendar1.getTime().toString());
It just prints the 10:11 am time of 1970 year. Like this - Fri Jan 02 10:11:13 IST 1970.
But I want to check if today's or any future date time falls in the range of 10 am to 6pm.
Below is the code reference:
public static Date convertCurrentTimeToSpecificTimeZone(String timeZone, int increaseDateBy,
int increaseMinutesBy) {
Calendar calendar = Calendar.getInstance();
TimeZone fromTimeZone = calendar.getTimeZone();
TimeZone toTimeZone = TimeZone.getTimeZone(timeZone);
calendar.setTimeZone(fromTimeZone);
calendar.add(Calendar.MILLISECOND, fromTimeZone.getRawOffset() * -1);
if (fromTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, calendar.getTimeZone().getDSTSavings() * -1);
}
calendar.add(Calendar.MILLISECOND, toTimeZone.getRawOffset());
if (toTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, toTimeZone.getDSTSavings());
}
increaseCalenderDateBy(calendar, increaseDateBy);
increaseCalenderMinuteBy(calendar, increaseMinutesBy);
return calendar.getTime();
}
public static void getTimeBetweenRange() throws ParseException {
String string1 = "10:11:13";
Date time1 = new SimpleDateFormat("HH:mm:ss").parse(string1);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);
calendar1.add(Calendar.DATE, 1);
System.out.println(calendar1.getTime().toString());
String string2 = "18:49:00";
Date time2 = new SimpleDateFormat("HH:mm:ss").parse(string2);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time2);
calendar2.add(Calendar.DATE, 1);
System.out.println(calendar2.getTime().toString());
Date d = convertCurrentTimeToSpecificTimeZone("America/Chicago", 2, 30);
Calendar calendar3 = Calendar.getInstance();
calendar3.setTime(d);
System.out.println(calendar3.getTime().toString());
Date x = calendar3.getTime();
if (x.after(calendar1.getTime()) && x.before(calendar2.getTime())) {
// checkes whether the current time is between 14:49:00 and 20:11:13.
System.out.println(true);
} else
System.out.println(false);
}
So the output for my below code is:
Fri Jan 02 10:11:13 IST 1970
Fri Jan 02 18:49:00 IST 1970
Fri Jan 31 03:15:07 IST 2020
It’s not very clear. For this answer I am assuming that all of your times are to be understood in America/Chicago time zone. Please revert if this was not what you intended.
java.time
ZoneId zone = ZoneId.of("America/Chicago");
ZonedDateTime zdt = ZonedDateTime.now(zone).plusDays(2).plusMinutes(30);
LocalTime rangeStart = LocalTime.parse("10:11:13");
LocalTime rangeEnd = LocalTime.parse("18:49:00");
LocalTime time = zdt.toLocalTime();
if (!time.isBefore(rangeStart) && time.isBefore(rangeEnd)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
When I ran this code snippet just now (at 11:30 Chicago time), the output was:
Yes
I am using java.time, the modern Java date and time API, and recommend that you do the same. It’s so much nicer to work with than the old, outdated and poorly designed classes Date, SimpleDateFormat, Calendar and TimeZone.
A LocalTime is a time of day from 00:00 (inclusive) to 24:00 (exclusive). By comparing LocalTimeobjects we are ignoring the date and have no trouble with irrelevant dates in 1970 or some other time in history.
Edit:
Also is it possible to get the date and time of rangeStart and
rangeEnd in order to verify for which particular day and time we are
checking the conditions?
No, that would not make sense. Since a LocalTime is a time of day without date, there is no way to get a date out of it. But you can print the ZonedDateTime and verify its date part. And to assure yourself that the code is correct, write some unit tests.
Link: Oracle tutorial: Date Time explaining how to use java.time.
A simple approach might be to parse your time Strings to instances of LocalTime and compare them. You have to decide if the start and end time are inclusive or not...
Support some formattings because you might have to pass Strings with AM/PM or without:
public static boolean isInTimeSlot(String time, String timeSlotStart, String timeSlotEnd) {
// create a formatter that supports different formats for the String arguments
DateTimeFormatter parserDtf = DateTimeFormatter.ofPattern("[hh:mm:ss a][HH:mm:ss][h a]");
// parse each argument to a LocalTime
LocalTime timeOfDay = LocalTime.parse(time, parserDtf);
LocalTime fromTime = LocalTime.parse(timeSlotStart, parserDtf);
LocalTime toTime = LocalTime.parse(timeSlotEnd, parserDtf);
// and return if the given time is in the time slot (including start and end time)
return timeOfDay.equals(fromTime) || timeOfDay.equals(toTime)
|| (timeOfDay.isAfter(fromTime) && timeOfDay.isBefore(toTime));
}
If you run it in a main like this
public static void main(String[] args) {
// provide some sample times
String[] times = { "10:31:17", "09:59:59", "6 PM", "4 AM", "06:00:01 PM" };
// provide a time slot
String from = "10 AM";
String to = "6 PM";
// check the method for each time string
for (String time : times) {
if (isInTimeSlot(time, from, to)) {
System.out.println(time + " is in the time slot at or between "
+ from + " and " + to);
} else {
System.err.println(time + " is not in the time slot at or between "
+ from + " and " + to);
}
}
}
the output will be
10:31:17 is in the time slot at or between 10 AM and 6 PM
09:59:59 is not in the time slot at or between 10 AM and 6 PM
6 PM is in the time slot at or between 10 AM and 6 PM
4 AM is not in the time slot at or between 10 AM and 6 PM
06:00:01 PM is not in the time slot at or between 10 AM and 6 PM
All I want to check if the current time from any timezone falls under the range of 10 am to 6 pm. If Yes, print "yes" else print "no".
For this, the following code will do the job.
LocalTime lt = LocalTime.now();
if( lt.isAfter( LocalTime.of( 10, 0 ) ) && lt.isBefore( LocalTime.of( 18, 0 ) ) ) System.out.println( "Yes" );
else System.out.println( "No" );
Since you have Date instances with you, you can convert them into LocalTime instances as shown below and use the same mechanism of comparison.
Date d = new Date(); //Change this to your way of creating the Date instance
LocalTime lt = LocalDateTime.ofEpochSecond( d.getTime(), 0, ZoneOffset.ofHours( 0 ) ).toLocalTime();
Hope this helps.
Date date= (new GregorianCalendar(year, month, day)).getTime();
SimpleDateFormat f = new SimpleDateFormat("EEEE");
String dow=f.format(date);
System.out.print("This date is a "+dow);
I have the user input a month(1-12) a day(1-31) and a year(1600-2400)
It works fine only it displays the wrong day. For example it says that Jan 1st 2014 is a Saturday but it was a Wednesday.
It is probably because I didn't factor in leap years but I don't have a clue to go about doing that. Neither do I know how to tell it how many days in each month. An array?
Hopefully minimal lines as well.
Thanks so much!!! This has been bugging me for an hour +. And something so simple, I should have figured. I must be tired.
Thanks!!!!!!!
Month is Zero based. Try,
Date date= (new GregorianCalendar(year, month-1, day)).getTime();
SimpleDateFormat f = new SimpleDateFormat("EEEE");
String dow=f.format(date);
The answer by Shashank Kadne is correct.
Joda-Time
FYI, this work is simpler and cleaner using the Joda-Time 2.3 library.
Joda-Time uses sensible one-based counting for things such as:
Month-of-YearJanuary = 1, February = 2, and so on.
Day-of-WeekMonday = 1, Sunday = 7. (Standard ISO 8601 week)
Joda-Time DateTime objects know their own time zone, unlike java.util.Date objects.
Joda-Time leverages a specified Locale object to render localized strings.
Example Code
// Specify a time zone rather than rely on default.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
int year = 2014;
int month = 1; // Sensible one-based counting. January = 1, February = 2, …
int dayOfMonth = 2;
DateTime dateTime = new DateTime( year, month, dayOfMonth, 0, 0, 0, timeZone );
// Day-of-week info.
int dayOfWeekNumber = dateTime.getDayOfWeek(); // Standard week (ISO 8601). Monday = 1, Sunday = 7.
DateTime.Property dayOfWeekProperty = dateTime.dayOfWeek();
String dayOfWeekName_Short = dayOfWeekProperty.getAsShortText( Locale.FRANCE );
String dayOfWeekName_Long = dayOfWeekProperty.getAsText( Locale.FRANCE );
Dump to console…
System.out.println( "dateTime: " + dateTime );
System.out.println( "dayOfWeekNumber: " + dayOfWeekNumber );
System.out.println( "dayOfWeekName_Short: " + dayOfWeekName_Short );
System.out.println( "dayOfWeekName_Long: " + dayOfWeekName_Long );
When run…
dateTime: 2014-01-02T00:00:00.000+01:00
dayOfWeekNumber: 4
dayOfWeekName_Short: jeu.
dayOfWeekName_Long: jeudi
Without Time & Time Zone
If you truly want only date without any time or time zone, then write similar code but with the LocalDate class.
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 am saving date's in a file in the following format as a string.
Sat Jul 21 23:31:55 EDT 2012
How can I check if 24 hours have passed? I am a beginner so please explain it a little bit =)
I am not sure if I completely understood the question - do you have two dates for comparison or do you wish to keep checking periodically if 24 hours have elapsed?
If comparing two date/times, I would suggest looking at joda or perhaps date4j. Using joda, one could look into using interval between two dates:
Interval interval = new Interval(previousTime, new Instant());
where previous time would be the time you mentioned
You can do something like this:
try {
// reading text...
Scanner scan = new Scanner( new FileInputStream( new File( "path to your file here..." ) ) );
String dateString = scan.nextLine();
// creating a formatter.
// to understand the format, take a look here: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
// EEE: Day name of week with 3 chars
// MMM: Month name of the year with 3 chars
// dd: day of month with 2 chars
// HH: hour of the day (0 to 23) with 2 chars
// mm: minute of the hour with 2 chars
// ss: second of the minute with 2 chars
// zzz: Timezone with 3 chars
// yyyy: year with 4 chars
DateFormat df = new SimpleDateFormat( "EEE MMM dd HH:mm:ss zzz yyyy", Locale.US );
// parsing the date (using the format above, that matches with your date string)
Date date = df.parse( dateString );
// now!
Date now = new Date();
// gets the differente between the parsed date and the now date in milliseconds
long diffInMilliseconds = now.getTime() - date.getTime();
if ( diffInMilliseconds < 0 ) {
System.out.println( "the date that was read is in the future!" );
} else {
// calculating the difference in hours
// one hour have: 60 minutes or 3600 seconds or 3600000 milliseconds
double diffInHours = diffInMilliseconds / 3600000D;
System.out.printf( "%.2f hours have passed!", diffInHours );
}
} catch ( FileNotFoundException | ParseException exc ) {
exc.printStackTrace();
}
I would suggest storing your information as a java.util.Calendar which has a compareTo ()function.
If you want to compare now to current time, you can use System.getCurrentTimeMillis() to get the current time.
Define A Day
Do you really mean one day or 24-hours? Because of Daylight Saving Time nonsense, a day can vary in length such as 23 or 25 hours in the United States.
Avoid 3-Letter Time Zone Codes
That String format is a terrible representation of a date-time. It is difficult to parse. It uses a 3-letter time zone code, and such codes are neither standardized nor unique. If possible, choose another format. The obvious choice is ISO 8601, for example: 2014-07-08T04:17:01Z.
Use proper time zone names.
Avoid j.u.Date & .Calendar
The java.util.Date and .Calendar classes bundled with Java are notoriously troublesome. Avoid them.
Instead use either the venerable Joda-Time library or the new java.time package bundled in Java 8 (and inspired on Joda-Time).
Joda-Time
Here is some example code in Joda-Time.
Get the current moment.
DateTime now = DateTime.now();
Parse the input string.
String input = "Sat Jul 21 23:31:55 EDT 2012";
DateTime formatter = DateTimeFormat.forPattern( "EEE MMM dd HH:mm:ss zzz yyyy" ).with Locale( java.util.Locale.ENGLISH );
DateTime target = formatter.parseDateTime( input );
Calculate 24 hours (or next day).
DateTime twentyFourHoursLater = target.plusHours( 24 );
Test if current moment happened after.
boolean expired = now.isAfter( twentyFourHoursLater );
Or, if you want next day rather than 24-hours, use plusDays rather than plusHours. If necessary, adjust to desired time zone. Time zone is crucial as it defines the day/date and applies rules for anomalies such as Daylight Saving Time.
DateTime targetAdjusted = target.withZone( DateTimeZone.forID( "Europe/Paris" ) );
…
DateTime aDayLater = targetAdjusted.plusDays( 1 ); // Go to next day, accounting for DST etc.
boolean expired = now.isAfter( aDayLater ); // Test if current moment happened after.
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);
}
}
}
}