I'm very new to Java. So please bear with me. I have 4 variables:
mode = prior|later|value;(can have either of these 3 values)
occurrence = 2
day = Wednesday
eta = 14:00
I'm trying to implement a method which will return a list date which is based on following criteria:
case 1 : (mode=prior,occurence=2,day=wednesday,eta=14:00)
should return dates of first 2 wednesdays of the next month from current month.
output = [Wed Aug 01 14:00:00 2018, Wed Aug 08 14:00:00 2018]
case 2 : (mode=later,occurence=2,day=wednesday,eta=14:00)
should return dates of last 2 wednesdays of the next month from current month.
output = [Wed Aug 22 14:00:00 2018, Wed Aug 29 14:00:00 2018]
case 3 : (mode=value,occurence=3,day=wednesday,eta=14:00)
should return date of 3rd wednesday of the next month from current month.
output = [Wed Aug 15 14:00:00 2018, Wed Aug 29 14:00:00 2018]
This is what I've done so far,
public static List<Date> getDates(Calendar c, String mode, int occurrence, int dayNo, String eta) {
List<Date> dates = new ArrayList<Date>();
switch(mode) {
case "value": {
String[] times = eta.split(":");
c.set(Calendar.DAY_OF_WEEK, dayNo);
c.set(Calendar.DAY_OF_WEEK_IN_MONTH, occurrence);
c.set(Calendar.MONTH, Calendar.JULY + 1);
c.set(Calendar.YEAR, 2018);
c.set(Calendar.HOUR_OF_DAY, Integer.parseInt(times[0]));
c.set(Calendar.MINUTE, Integer.parseInt(times[1]));
dates.add(c.getTime());
}
}
return dates;
}
Is there a better way of doing what I've done. Also can somebody please help me with implementing the cases 1 and 2 ?
Avoid legacy date-time classes
You are using terrible old date-time classes that were supplanted years ago by the java.time classes.
In particular, the Calendar class (well, actually, GregorianCalendar) is replaced by ZonedDateTime.
Use types (classes)
Use smart objects rather than dumb strings, where feasible. Using appropriate types makes your code more self-documenting, ensures valid values, provides for type-safety, and lets the compiler catch your typos.
In your case, Java already provides types for most of your data. You can make your own type for the “mode”.
The enum facility in Java is much more powerful and flexible than typically seen in other languages. See Oracle Tutorial to learn more. But the basics are simple, as seen here:
public enum Mode {
PRIOR ,
LATER ,
VALUE
}
For day-of-week, use the DayOfWeek enum, pre-defining seven objects, one for each day of the week. For example, DayOfWeek.WEDNESDAY.
For time-of-day, use LocalTime.
LocalTime lt = LocalTime.of( 14 , 0 ) ;
For the current month, use YearMonth class.
Determining the current year-month means determining the current date. Determining the current date requires a time zone. For any given moment, the date varies around the globe by zone.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ; // Or "America/Chicago", etc.
YearMonth ym = YearMonth.now( z ) ;
If you have a LocalDate, you can determine the year-month for it.
YearMonth ym = YearMonth.from( myLocalDate ) ;
I suggest having the calling method determine the YearMonth rather than make this method jump through extra hoops. A general design approach in OOP is to separate, or disentangle, responsibilities. This method we are writing should be concerned with its own needs (a year-month value) and should not have to care about how the calling method arrives at its desired year-month whether that be from current date or current month or last month, etc.
Lastly, if your goal is to get a moment in time (a date with a time-of-day), then you must also specify a time zone. A date+time without the context of a time zone (or offset-from-UTC) has no real meaning.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
So, putting this all together, your method signature could look like this:
public static List< ZonedDateTime > getDates(
YearMonth ym ,
Mode mode ,
int occurrences ,
DayOfWeek dow ,
LocalTime lt ,
ZoneId z
) { …
Logic
The solution to your first two cases, Mode.PRIOR and Mode.LATER, is the use of the TemporalAdjuster interface. Specifically, the implementations found in TemporalAdjusters class can determine the “nth” weekday-of-month such as first Wednesday. Even more specifically:
firstInMonth( DayOfWeek dayOfWeek )
lastInMonth( DayOfWeek dayOfWeek )
The main idea here is to start with the first (or last) day-of-week in the month. Then work our way down (up) through the month, week-by-week, adding (subtracting) a week at a time. Repeat for our limit of integer occurrences.
We can do a switch on our Mode enum, as discussed here. Minor point: I would prefer to use Mode.PRIOR syntax rather than just PRIOR, for clarity. However, an obscure technicality in Java forbids that syntax in a switch. So, case PRIOR: not case Mode.PRIOR:, as shown further down in sample code.
We collect our resulting ZonedDateTime objects in a List named moments.
int initialCapacity = 5; // Max five weeks in any month.
List< ZonedDateTime > moments = new ArrayList<>( initialCapacity );
Let’s look at the logic for each of our three modes.
Mode.PRIOR
Get the first day-of-week of the month.
LocalDate firstDowOfMonth = ym.atDay( 1 ).with( TemporalAdjusters.firstInMonth( dow ) );
Work our way down through the month, adding a week at a time.
We might exceed the bounds of the month, going into the following month. So check the YearMonth to see if it is the same as when when started.
for ( int i = 0 ; i < occurrences ; i++ ) {
LocalDate ld = firstDowOfMonth.plusWeeks( i );
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z );
if ( YearMonth.from( zdt ).equals( ym ) ) { // If in same month…
moments.add( zdt );
}
}
Mode.LATER
This case uses the same logic as above, except we start at the bottom of the month and work our way up. Get the last day-of-week of month, then subtract a week at a time.
// Start with last day-of-week in month.
LocalDate lastDowOfMonth = ym.atDay( 1 ).with( TemporalAdjusters.lastInMonth( dow ) );
// Work our way up through the month, subtracting a week at a time.
for ( int i = 0 ; i < occurrences ; i++ ) {
LocalDate ld = lastDowOfMonth.minusWeeks( i );
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z );
if ( YearMonth.from( zdt ).equals( ym ) ) { // If in same month…
moments.add( zdt );
}
}
Because we are going backwards through time, our collection of moments is in reverse chronological order. So, we need to sort to present these in chronological order.
Collections.sort( moments ); // If you want the list to be in chronological order, sort. Otherwise in reverse chronological order for this `Mode.LATER`.
Mode.VALUE
The last case is the simplest: Get the nth day-of-week in the month. That is simply a one-liner.
LocalDate nthDowInMonth = ym.atDay( 1 ).with( TemporalAdjusters.dayOfWeekInMonth( occurrences , dow ) );
Do the usual, make a ZonedDateTime.
ZonedDateTime zdt = ZonedDateTime.of( nthDowInMonth , lt , z );
Verify the month, as the documentation seems to be saying that exceeding the limits of the month takes us into the next month. In such a case, our logic omits the date from our list. So we will be returning moments as an empty list. This means the calling method should check for the list having elements, as it may be empty.
if ( YearMonth.from( zdt ).equals( ym ) ) { // If in same month…
moments.add( zdt );
}
Let’s see all the code put together.
// Simulate arguments passed.
LocalTime lt = LocalTime.of( 14 , 0 );
ZoneId z = ZoneId.of( "Africa/Tunis" ); // Or "America/Chicago", etc.
YearMonth ym = YearMonth.now( z );
DayOfWeek dow = DayOfWeek.WEDNESDAY;
Mode mode = Mode.PRIOR ; // Mode.PRIOR, Mode.LATER, Mode.VALUE.
int occurrences = 3; // TODO: Add code to verify this value is in range of 1-5, not zero, not >5.
// Logic
int initialCapacity = 5; // Max five weeks in any month.
List< ZonedDateTime > moments = new ArrayList<>( initialCapacity );
switch ( mode ) {
case PRIOR:
// Start with first day-of-week in month.
LocalDate firstDowOfMonth = ym.atDay( 1 ).with( TemporalAdjusters.firstInMonth( dow ) );
// Work our way down through the month, adding a week at a time.
for ( int i = 0 ; i < occurrences ; i++ ) {
LocalDate ld = firstDowOfMonth.plusWeeks( i );
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z );
if ( YearMonth.from( zdt ).equals( ym ) ) { // If in same month…
moments.add( zdt );
}
}
break;
case LATER:
// Start with last day-of-week in month.
LocalDate lastDowOfMonth = ym.atDay( 1 ).with( TemporalAdjusters.lastInMonth( dow ) );
// Work our way up through the month, subtracting a week at a time.
for ( int i = 0 ; i < occurrences ; i++ ) {
LocalDate ld = lastDowOfMonth.minusWeeks( i );
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z );
if ( YearMonth.from( zdt ).equals( ym ) ) { // If in same month…
moments.add( zdt );
}
}
Collections.sort( moments ); // If you want the list to be in chronological order, sort. Otherwise in reverse chronological order for this `Mode.LATER`.
break;
case VALUE:
// Get the nth day-of-week in month.
LocalDate nthDowInMonth = ym.atDay( 1 ).with( TemporalAdjusters.dayOfWeekInMonth( occurrences , dow ) );
ZonedDateTime zdt = ZonedDateTime.of( nthDowInMonth , lt , z );
if ( YearMonth.from( zdt ).equals( ym ) ) { // If in same month…
moments.add( zdt );
}
break;
default: // Defensive programming, testing for unexpected values.
System.out.println( "ERROR - should not be able to reach this point. Unexpected `Mode` enum value." );
break;
}
// return `moments` list from your method.
System.out.println( "moments:\n" + moments );
Note that the specified time-of-day on a particular date in our specified time zone may not be valid. For example, during a cutover in Daylight Saving Time (DST). If so, the ZonedDateTime class adjusts as needed. Be sure to read the documentation to make sure you understand and agree to its adjustment algorithm.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
So as I understand your question I wrote some code for example. I could not understand the "value" option. Desired output and explanation of method is not obvious for me. If you explain it I could edit the answer.
public class Main {
public static void main(String[] args) {
for (String s : findOccurence("prior", DayOfWeek.WEDNESDAY, 2, "14:00")){
System.out.println(s);
}
}
public static String[] findOccurence(String mode, DayOfWeek day, int occurrence, String eta) {
LocalDate now = LocalDate.now();
LocalDate start = LocalDate.of(now.getYear(), now.getMonth().plus(1), 1);
LocalDate finish = start.plusDays(start.lengthOfMonth());
List<LocalDate> dates = Stream.iterate(start, date -> date.plusDays(1))
.limit(ChronoUnit.DAYS.between(start, finish))
.filter(d -> d.getDayOfWeek() == day)
.collect(Collectors.toList());
String[] formattedEta = eta.split(":");
if (occurrence > dates.size()) {
throw new IndexOutOfBoundsException();
}
if (mode.equalsIgnoreCase("value")) {
}
else if (mode.equalsIgnoreCase("later")) {
dates = Lists.reverse(dates);
}
//later and prior shares common logic
return dates.stream()
.limit(occurrence)
.map(d -> day.toString()
+ " "
+ start.getMonth().name()
+ " "
+ d.getDayOfMonth()
+ " "
+ LocalTime.of(Integer.valueOf(formattedEta[0]), Integer.valueOf(formattedEta[1]), 0)
+ " "
+ start.getYear())
.collect(Collectors.toList())
.toArray(new String[occurrence]);
}
}
Output is :
WEDNESDAY AUGUST 1 14:00 2018
WEDNESDAY AUGUST 8 14:00 2018
Related
I am new to Java and I already have c# code which I have to convert it into java, but am not able to find good alternative to it.
Below is the code that I want to convert:
private string GetDate(object value)
{
DateTime start = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var lastWeek = DateTime.Today.AddDays(-6);
var date = start.AddMilliseconds((long)value).ToLocalTime();
if (date >= lastWeek)
{
if (date.DayOfWeek == DateTime.Now.DayOfWeek)
return "Today";
else
return date.DayOfWeek.ToString();
}
else
return date.ToString("dd-MM-yyy");
}
I tried using Calendar class at first, but it's giving error that integer number too large:
Calendar cal = Calendar.getInstance();
cal.set(1970, 0, 1, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
long result = cal.getTimeInMillis();
long value = result + 1406205185123;
Any solution/suggestion will be helpful.
I haven't checked if it satisfies all your requirements regarding the output, but I think it will give enough pointers to help you out. Depending on your needs you need a ZonedDateTime (which has a timezone), or a LocalDateTime, which is the date as people speak about it in a country.
private String getDate(long value) {
LocalDateTime now = LocalDateTime.now();
LocalDateTime start = LocalDateTime.of(1970, 1, 1, 0, 0, 0, 0);
LocalDateTime lastWeek = now.minusDays(6);
LocalDateTime date = start.plus(value, ChronoUnit.MILLIS);
if (lastWeek.isBefore(date)) {
DayOfWeek dayOfWeek = date.getDayOfWeek();
if (dayOfWeek == now.getDayOfWeek()) {
return "Today";
} else {
return dayOfWeek.name();
}
}
return date.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT));
}
I've also took the liberty to convert the code style to what is usual in Java, which is the placing of the opening brace, the capitalization of functions.
More on the date/time classes can be found in the Oracle Trail on date/time.
tl;dr
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ; // The time zone of your business context.
LocalDate input = Instant.ofEpochMilli( yourMillis ).atZone( z ).toLocalDate() ;
LocalDate today = LocalDate.now( z ) ;
LocalDate weekAgo = today.minusDays( 6 ) ;
if ( input.isAfter( today ) ) { … error }
else if ( input.isEqual( today ) ) { return "Today" ; }
else if ( ! input.isBefore( weekAgo ) ) { return input.getDayOfWeek().getDisplayName( TextStyle.FULL , Locale.US ) ; }
else if ( input.isBefore( weekAgo ) ) { return input.format( DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ) ; }
else { … error, unreachable point }
Details
DateTime start = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
Instead, for a point on the timeline in UTC, use Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Your example of first moment of 1970 UTC happens to be the epoch reference used by the java.time framework. And it happens to be defined as a constant.
Instant start = Instant.EPOCH ;
Add your count of milliseconds.
Instant later = start.plusMillis( yourMillis ) ;
But if your count of milliseconds is always a count since the epoch reference, then you can shorten that code above.
Instant instantInput = Instant.ofEpochMilli( yourMillis ) ; // Determine a moment in UTC from a count of milliseconds since 1970-01-01T00:00Z.
Apparently your goal is to compare dates or day-of-week. Both of those require a time zone. You ignore this crucial issue in your Question. For any given moment, the date varies around the globe by zone. At this moment right now is Monday in the United States, but in New Zealand it is “tomorrow” Tuesday.
Apply a ZoneId to get a ZonedDateTime. Same moment, same point on the timeline, but seen through the wall-clock time used by the people of a particular region (a time zone).
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdtInput = instantInput.atZone( z ) ;
Extract the date-only, without a time-of-day and without a time zone.
LocalDate ldInput = zdtInput.toLocalDate() ;
Extract the day-of-week, represented by the DayOfWeek enum.
DayOfWeek dowInput = ldInput.getDayOfWeek() ;
Subtract six days from now. Represent the six days as TemporalAmount, either six calendar days in a Period or six chunks of 24-hours as a Duration.
Period sixDays = Period.ofDays( 6 ) ;
LocalDate today = LocalDate.now( z ) ;
LocalDate sixDaysBeforeToday = today.minus( sixDays ); // Or LocalDate.now( z ).plusDays( 6 )
Compare. Let's simplify your branching logic. We will work chronologically in reverse order through five cases: future, today, past six days, prior, impossible.
if( ldInput.ifAfter( today ) ) {
System.out.println( "ERROR - input is in the future. Not expected." ) ;
} else if( ldInput.isEqual( today ) ) {
return "Today" ;
} else if ( ! ldInput.isBefore( sixDaysBeforeToday ) ) { // A shorter way of asking "is equal to OR later" is asking "is NOT before".
return dowInput.getDisplayName( TextStyle.FULL , Locale.US ) ; // Let java.time localize the name of the day-of-week.
} else if ( ldInput.isBefore ( sixDaysBeforeToday ) ) {
return ldInput.format( DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ) ;
} else {
System.out.println( "ERROR - Reached impossible point." ) ; // Defensive programming.
}
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
In a form, I have 4 fields where the user can select the date in a list to search for an event that happened on that date:
year
month
day
hour
So far it works only when none of the fields is selected (so the result is all the events that ever happened), or only when all fields are selected (so the result is all events that happened in that hour of that day of that month of that year).
My problem is that I don't know how to search if only a month or a year and an hour is selected (all 4^4 combinations possible). How can I achieve this?
Your Question is vague as it does not address your goal. I will assume you are gathering input for some kind of query against a date range.
So I suppose it makes sense to have a year alone, or a year+month, or a year+month+dayOfMonth, or a year+month+dayOfMonth+Hour but no other combinations.
Date-time values
Use the java.time classes to determine dates or date-times for searching.
For year only, use Year class.
if( yearOnly ) {
Year year = Year.of( Integer.intValue( yearFieldValue ) );
LocalDate yearStartDate = year.atDay( 1 );
LocalDate yearStopDate = year.atDay( year.length() ); // Year is normally 365 or 366 days long ([Leap Year][2]).
}
Or if you are wisely using the Half-Open approach to defining a span of time, where the beginning is inclusive while the ending is exclusive that would mean a year starts on the first of the year and runs up to, but does not include, the first of the following year.
if( yearOnly ) {
Year year = Year.of( Integer.intValue( yearFieldValue ) );
LocalDate targetYearStartDate = year.atDay( 1 );
LocalDate followingYearStartDate = targetYearStartDate.plusYears( 1 );
}
If you need exact moments, get the first moment of each day. Specify a time zone as when the date starts varies around the globe by zone. Apply a ZoneId to get a ZonedDateTime object.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdtStart = targetYearStartDate.atStartOfDay( z );
ZonedDateTime zdtStop = followingYearStartDate.atStartOfDay( z );
If they provide year and month but no date and no hour, use YearMonth.
YearMonth ymStart = YearMonth.of( Integer.intValue( yearFieldValue ) , Integer.intValue( monthFieldValue ) );
LocalDate ldStart = ymStart.atDay( 1 );
LocalDate ldStop = ym.plusMonths( 1 ).atDay( 1 );
If you get year and month and day-of-month, do straight to a LocalDate.
LocalDate ld = LocalDate.of(
Integer.intValue( yearFieldValue ) ,
Integer.intValue( monthFieldValue ) ,
Integer.intValue( dayOfMonthFieldValue )
)
If you also get an hour, then construct a LocalTime. Combine with LocalDate and ZoneId to get a ZonedDateTime object.
LocalTime lt = LocalTime.of( Integer.intValue( hourFieldValue ) , 0 );
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z );
User Interface
In terms of user interface, you could enable only the year field at first. Once a valid value is entered, enable the next field, and so on.
If you cannot do that, then one approach is to not address bad entries. If they enter year and dayOfMonth but no month, just go with searching for the entire year, for example.
If you want to address bad data entry, then you need to do the checking with your code, looking for each good and bad combination.
I'm trying to make an ArrayList with Holidays and dates (both Strings), then convert date to Calendar, get the day of week (using DAY_OF_WEEK) and/or sort by date/name, but for some reason I get the same result (Calendar) for every item on the list.
This is my code:
public static ArrayList listOfHolidays = new ArrayList();
Holidays.holidaysList.add(new Holidays("Sukkot", "09/10/2014"));
Holidays.holidaysList.add(new Holidays("Hanukkah", "17/12/2014"));
Holidays.holidaysList.add(new Holidays("Purim", "16/03/2014"));
Holidays class:
Calendar calendar = Calendar.getInstance();
#Override
public String toString() {
//DayOfWeek is just an enum of days (strings)
return holidayName + " falls on "
+ DayOfWeek.values()[Calendar.DAY_OF_WEEK - 1]; // Here i get the same day each time
}
#Override
public int compareTo(Holidays another) {
if(MainActivity.sortByName == true) {
return holidayName.compareToIgnoreCase(another.holidayName);
}
return convertStringToCal() - another.convertStringToCal();
}
private int convertStringToCal() {
int year, month, day;
day = Integer.valueOf(holidayDate.substring(0, 2));
month = Integer.valueOf(holidayDate.substring(3, 5));
year = Integer.valueOf(holidayDate.substring(6, 10));
calendar = Calendar.getInstance();
calendar.set(year, month, day);
return (int) calendar.getTimeInMillis();
}
I call Collections.sort() from within a radioButton method to sort.
I see multiple reasons why it may not work.
First i don't know if you omitted part of the code of you Holidays class but you never actually set the calendar object aside from the convertStringToCal() method but i don't see if this method is also called in the constructor.
Secondly and most likely your problem:
#Override
public String toString() {
//DayOfWeek is just an enum of days (strings)
return holidayName + " falls on "
// Here you are using the constant Calendar.DAY_OF_WEEK
+ DayOfWeek.values()[Calendar.DAY_OF_WEEK - 1]; // Here i get the same day each time
}
It should actually look something like this:
#Override
public String toString() {
//DayOfWeek is just an enum of days (strings)
return holidayName + " falls on "
+ DayOfWeek.values()[calendar.get(Calendar.DAY_OF_WEEK)]; // Now you won't get the same day every time. :)
}
Some additional notes:
I would use Date objects to hold the dates, and use SimpleDateFormat to convert Strings to Dates and the other way around.
If you use these two your Holidays class would look something like this:
public class Holidays {
private final Calendar calendar = Calendar.getInstance();
private final String holidayName;
public Holidays(String holidayName, Date date) {
this.holidayName = holidayName;
this.calendar.setTime(date);
}
#Override
public int compareTo(Holidays another) {
// Generally you should avoid passing information statically between Activities
if(MainActivity.sortByName == true) {
return holidayName.compareToIgnoreCase(another.holidayName);
}
return getTimeInMillis() - another.getTimeInMillis();
}
public long getTimeInMillis() {
return this.calendar.getTimeInMillis();
}
#Override
public String toString() {
//DayOfWeek is just an enum of days (strings)
DayOfWeek day = DayOfWeek.values()[calendar.get(Calendar.DAY_OF_WEEK)]; // Now you won't get the same day every time. :)
return String.format("%s falls of %s", this.holidayName, day);
}
}
You can create Date objects like this:
// Create date objects with calendar.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2014);
calendar.set(Calendar.MONTH, 3);
calendar.set(Calendar.DAY_OF_MONTH, 27);
Date date = calendar.getTime();
The Constructors of the Date object like new Date(year, month, day) are deprecated and should not be used. Always use a Calendar instance to create date objects.
With SimpleDateFormat you can convert String and Date objects like this:
// The String pattern defines how date strings are parsed and formated
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String dateString = "09/10/2014";
// Convert a String to Date
Date dateFromDateString = sdf.parse(dateString);
// Convert a Date to a String
String dateStringFromDate = sdf.format(dateFromDateString);
If you need more than just simple conversion of Date and String objects you can use DateFormat. That is pretty much the Rolls Royce of Date String conversion. It can parse and format Strings in a much more general way without actually requiring a pattern and it automatically accounts for locale and much more.
Or you could just use JodaTime :)
I think the problem is in casting to int in this part of code:
return (int) calendar.getTimeInMillis();
calendar.getTimeInMillis() returns long, and casting to int should cause a problem.
tl;dr
holidays.add(
new Holiday(
LocalDate.of( 2018 , Month.MAY , 8 ) ,
"National Coconut Cream Pie Day"
)
)
java.time
This work is so much simpler with the modern java.time classes rather than obsolete legacy Calendar class and its commonly-used subclass, GregorianCalendar.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.
LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ; // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.
Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety.
LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;
Custom class
You misused the name Holidays twice in your code, once as the name of the list collection and once as the name of the individual "holiday" class/object. Furthermore, the first used as holding a static class variable, not likely a good design.
I will assume the second is a typo, and the second should be Holiday as the name of the class representing a particular holiday on a particular date.
Your Holiday class would look something like this.
class Holiday
{
private LocalDate localDate;
private String name;
private DayOfWeek dow;
public Holiday ( LocalDate localDateArg , String nameArg )
{
this.localDate = localDateArg;
this.name = nameArg;
}
public LocalDate getLocalDate ( )
{
return localDate;
}
public String getName ( )
{
return name;
}
// With arguments.
public String format ( Locale locale , FormatStyle style )
{
String date = this.localDate.format( DateTimeFormatter.ofLocalizedDate( style ).withLocale( locale ) );
String output = date + " | " + this.name;
return output;
}
#Override
public String toString ( )
{
return "Holiday{ " +
"localDate=" + localDate +
", name='" + name + '\'' +
" }";
}
}
Next, we use that class.
List
Instantiate an empty List. You can optionally set the initial capacity of the ArrayList.
List < Holiday > holidays = new ArrayList <>( 3 );
Populate that list.
holidays.add( new Holiday( LocalDate.of( 2018 , Month.MAY , 8 ) , "National Coconut Cream Pie Day" ) );
holidays.add( new Holiday( LocalDate.of( 2018 , Month.AUGUST , 9 ) , "National Rice Pudding Day" ) );
holidays.add( new Holiday( LocalDate.of( 2018 , Month.JANUARY , 5 ) , "National Whipped Cream Day" ) );
holidays.toString():
[Holiday{ localDate=2018-05-08, name='National Coconut Cream Pie Day' }, Holiday{ localDate=2018-08-09, name='National Rice Pudding Day' }, Holiday{ localDate=2018-01-05, name='National Whipped Cream Day' }]
Sort with Comparator
To sort, pass an implementation of Comparator. Here is the classic Java syntax.
holidays.sort( new Comparator < Holiday >()
{
#Override
public int compare ( Holiday o1 , Holiday o2 )
{
int c = o1.getLocalDate().compareTo( o2.getLocalDate() );
return c;
}
} );
Here is that same Comparator in modern Java syntax using a lambda.
holidays.sort( ( o1 , o2 ) ->
{
int c = o1.getLocalDate().compareTo( o2.getLocalDate() );
return c;
} );
Or even shorter lambda syntax, but not necessarily better.
holidays.sort( ( o1 , o2 ) -> o1.getLocalDate().compareTo( o2.getLocalDate() ) );
Either way, the results are:
holidays.toString():
[Holiday{ localDate=2018-01-05, name='National Whipped Cream Day' }, Holiday{ localDate=2018-05-08, name='National Coconut Cream Pie Day' }, Holiday{ localDate=2018-08-09, name='National Rice Pudding Day' }]
Formatting output
For your date with day-of-week, use the format method we defined that automatically localized to the human language and cultural norms we specify with a Locale and FormatStyle.
for ( Holiday holiday : holidays )
{
System.out.println( holiday.format( Locale.CANADA_FRENCH , FormatStyle.FULL ) );
}
vendredi 5 janvier 2018 | National Whipped Cream Day
mardi 8 mai 2018 | National Coconut Cream Pie Day
jeudi 9 août 2018 | National Rice Pudding Day
Or in US English, passing Locale.US:
Friday, January 5, 2018 | National Whipped Cream Day
Tuesday, May 8, 2018 | National Coconut Cream Pie Day
Thursday, August 9, 2018 | National Rice Pudding Day
Note that you can get a DayOfWeek enum object from LocalDate. From that you can automatically localize the name of that day with the DayOfWeek::getDisplayName method.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
This question already has answers here:
how to get a list of dates between two dates in java
(23 answers)
Closed 6 years ago.
I attempted to generate the date range between date x and date y but failed. I have the same method in c# so I tried to modify it as much as I can but failed to get result. Any idea what I could fix?
private ArrayList<Date> GetDateRange(Date start, Date end) {
if(start.before(end)) {
return null;
}
int MILLIS_IN_DAY = 1000 * 60 * 60 * 24;
ArrayList<Date> listTemp = new ArrayList<Date>();
Date tmpDate = start;
do {
listTemp.add(tmpDate);
tmpDate = tmpDate.getTime() + MILLIS_IN_DAY;
} while (tmpDate.before(end) || tmpDate.equals(end));
return listTemp;
}
To be honest I was trying to get all the dates starting from january 1st till the end of year 2012 that is december 31st. If any better way available, please let me know.
Thanks
Joda-Time
Calendar and Date APIs in java are really weird... I strongly suggest to consider jodatime, which is the de-facto library to handle dates.
It is really powerful, as you can see from the quickstart: http://joda-time.sourceforge.net/quickstart.html.
This code solves the problem by using Joda-Time:
import java.util.ArrayList;
import java.util.List;
import org.joda.time.DateTime;
public class DateQuestion {
public static List<DateTime> getDateRange(DateTime start, DateTime end) {
List<DateTime> ret = new ArrayList<DateTime>();
DateTime tmp = start;
while(tmp.isBefore(end) || tmp.equals(end)) {
ret.add(tmp);
tmp = tmp.plusDays(1);
}
return ret;
}
public static void main(String[] args) {
DateTime start = DateTime.parse("2012-1-1");
System.out.println("Start: " + start);
DateTime end = DateTime.parse("2012-12-31");
System.out.println("End: " + end);
List<DateTime> between = getDateRange(start, end);
for (DateTime d : between) {
System.out.println(" " + d);
}
}
}
You could use this function:
public static Date addDay(Date date){
//TODO you may want to check for a null date and handle it.
Calendar cal = Calendar.getInstance();
cal.setTime (date);
cal.add (Calendar.DATE, 1);
return cal.getTime();
}
Found here.
And what is the reason of fail? Why you think that your code is failed?
tl;dr
Year year = Year.of ( 2012 ) ; // Represent an entire year.
year
.atDay( 1 ) // Determine the first day of the year. Returns a `LocalDate` object.
.datesUntil( // Generates a `Stream<LocalDate>`.
year
.plusYears( 1 ) // Returns a new `Year` object, leaving the original unaltered.
.atDay( 1 ) // Returns a `LocalDate`.
) // Returns a `Stream<LocalDate>`.
.forEach( // Like a `for` loop, running through each object in the stream.
System.out :: println // Each `LocalDate` object in stream is passed to a call of `System.out.println`.
)
;
java.time
The other Answers are outmoded as of Java 8.
The old date-time classes bundled with earlier versions of Java have been supplanted with the java.time framework built into Java 8 and later. See Tutorial.
LocalDate (date-only)
If you care only about the date without the time-of-day, use the LocalDate class. The LocalDate class represents a date-only value, without time-of-day and without time zone.
LocalDate start = LocalDate.of( 2016 , 1 , 1 ) ;
LocalDate stop = LocalDate.of( 2016 , 1 , 23 ) ;
To get the current date, specify a time zone. For any given moment, today’s date varies by time zone. For example, a new day dawns earlier in Paris than in Montréal.
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );
We can use the isEqual, isBefore, and isAfter methods to compare. In date-time work we commonly use the Half-Open approach where the beginning of a span of time is inclusive while the ending is exclusive.
List<LocalDate> localDates = new ArrayList<>();
LocalDate localDate = start;
while ( localDate.isBefore( stop ) ) {
localDates.add( localDate );
// Set up the next loop.
localDate = localDate.plusDays( 1 );
}
LocalDate::datesUntil
You can obtain a stream of LocalDate objects.
Stream< LocalDate > dates = start.datesUntil( stop ) ;
dates.forEach( System.out::println ) ;
LocalDateRange
If doing much of this work, add the ThreeTen-Extra library to your project. This gives you the LocalDateRange class to represent your pair of start and stop LocalDate objects.
Instant (date-time)
If you have old java.util.Date objects, which represent both a date and a time, convert to the Instant class. An Instant is a moment on the timeline in UTC.
Instant startInstant = juDate_Start.toInstant();
Instant stopInstant = juDate_Stop.toInstant();
From those Instant objects, get LocalDate objects by:
Applying the time zone that makes sense for your context to get ZonedDateTime object. This object is the very same moment on the timeline as the Instant but with a specific time zone assigned.
Convert the ZonedDateTime to a LocalDate.
We must apply a time zone as a date only has meaning within the context of a time zone. As we said above, for any given moment the date varies around the world.
Example code.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate start = ZonedDateTime.ofInstant( startInstant , zoneId ).toLocalDate();
LocalDate stop = ZonedDateTime.ofInstant( stopInstant , zoneId ).toLocalDate();
You can use joda-time.
Days.daysBetween(fromDate, toDate);
Found at joda-time homepage.
similar question in stackoverflow with some good answers.
Look at the Calendar API, particularly Calendar.add().
What this code does is print the dates of the current week from Monday to Friday. It works fine, but I want to ask something else: If today is Saturday or Sunday I want it to show the next week. How do I do that?
Here's my working code so far (thanks to StackOverflow!!):
// 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 to Friday
DateFormat df = new SimpleDateFormat("EEE dd/MM/yyyy");
for (int i = 0; i <= 4; i++) {
System.out.println(df.format(c.getTime()));
c.add(Calendar.DATE, 1);
}
Thanks a lot! I really appreciate it as I've been searching for the solution for hours...
public static void main(String[] args) {
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 to Friday
DateFormat df = new SimpleDateFormat("EEE dd/MM/yyyy");
for (int i = 0; i <= 10; i++) {
System.out.println(df.format(c.getTime()));
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == Calendar.FRIDAY) { // If it's Friday so skip to Monday
c.add(Calendar.DATE, 3);
} else if (dayOfWeek == Calendar.SATURDAY) { // If it's Saturday skip to Monday
c.add(Calendar.DATE, 2);
} else {
c.add(Calendar.DATE, 1);
}
// As Cute as a ZuZu pet.
//c.add(Calendar.DATE, dayOfWeek > Calendar.THURSDAY ? (9 - dayOfWeek) : 1);
}
}
Output
Mon 03/01/2011
Tue 04/01/2011
Wed 05/01/2011
Thu 06/01/2011
Fri 07/01/2011
Mon 10/01/2011
Tue 11/01/2011
Wed 12/01/2011
Thu 13/01/2011
Fri 14/01/2011
Mon 17/01/2011
If you want to be cute you can replace the if/then/else with
c.add(Calendar.DATE, dayOfWeek > 5 ? (9 - dayOfWeek) : 1);
but I really wanted something easily understood and readable.
tl;dr
Core code concept:
EnumSet.of( DayOfWeek.SATURDAY , DayOfWeek.SUNDAY ) // Instantiate a n implementation of `Set` highly optimized in both memory usage and execution speed for collecting enum objects.
.contains( // Ask if our target `DayOfWeek` enum object is in our `Set`.
LocalDate.now( ZoneId.of( "America/Montreal" ) ) // Determine today’s date as seen by the people of a particular region (time zone).
.getDayOfWeek() // Determine the `DayOfWeek` enum constant representing the day-of-week of this date.
)
java.time
The modern way is with the java.time classes.
The DayOfWeek enum provides seven objects, for Monday-Sunday.
The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
DayOfWeek dow = today.getDayOfWeek();
Define the weekend as a set of DayOfWeek objects. Note that EnumSet is an especially fast and low-memory implementation of Set designed to hold Enum objects such as DayOfWeek.
Set<DayOfWeek> weekend = EnumSet.of( DayOfWeek.SATURDAY , DayOfWeek.SUNDAY );
Now we can test if today is a weekday or a weekend.
Boolean todayIsWeekend = weekend.contains( dow );
The Question said we want to jump to the start of next week if this is a weekend. To do that, use a TemporalAdjuster which provides for classes that can manipulate date-time objects. In java.time we have immutable objects. This means we produce new instances based on the values within an existing object rather than alter ("mutate") the original. The TemporalAdjusters class (note the plural 's') provides several handy implementations of TemporalAdjuster including next( DayOfWeek ).
DayOfWeek firstDayOfWeek = DayOfWeek.MONDAY ;
LocalDate startOfWeek = null ;
if( todayIsWeekend ) {
startOfWeek = today.with( TemporalAdjusters.next( firstDayOfWeek ) );
} else {
startOfWeek = today.with( TemporalAdjusters.previousOrSame( firstDayOfWeek ) );
}
We soft-code the length of the week in case our definition of weekend ever changes.
LocalDate ld = startOfWeek ;
int countDaysToPrint = ( DayOfWeek.values().length - weekend.size() );
for( int i = 1 ; i <= countDaysToPrint ; i++ ) {
System.out.println( ld );
// Set up the next loop.
ld = ld.plusDays( 1 );
}
See live code in IdeOne.com.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Here is short answer using Java 8, all you need to do is to convert your Calendar instance to LocalDateTime and leverage DayOfWeek enum to check if it's Saturday or Sunday, here you go...
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
DateFormat df = new SimpleDateFormat("EEE dd/MM/yyyy");
for (int i = 0; i <= 20; i++) {
//following line does all magic for you
if(LocalDateTime.ofInstant(c.toInstant(), ZoneId.systemDefault()).getDayOfWeek()!=DayOfWeek.SATURDAY && LocalDateTime.ofInstant(c.toInstant(), ZoneId.systemDefault()).getDayOfWeek()!=DayOfWeek.SUNDAY)
System.out.println(df.format(c.getTime()));
c.add(Calendar.DATE, 1);
}