I am using Joda time api in a Spring 3.0 project for the very first time. Now I have a start and end date and I want to get the date for all mondays between these two dates. How can I do this ?
I have no idea where to start, can someone please advise. I looked at theis post Joda Time: How to get dates of weekdays on some date interval? and it offered some sort of guidance but its still somewhat vague due to little experience with joda.
LocalDate startDate = new LocalDate(2011, 11, 8);
LocalDate endDate = new LocalDate(2012, 5, 1);
LocalDate thisMonday = startDate.withDayOfWeek(DateTimeConstants.MONDAY);
if (startDate.isAfter(thisMonday)) {
startDate = thisMonday.plusWeeks(1); // start on next monday
} else {
startDate = thisMonday; // start on this monday
}
while (startDate.isBefore(endDate)) {
System.out.println(startDate);
startDate = startDate.plusWeeks(1);
}
I recently developed Lamma which is designed to solve this exact use case:
Dates.from(2011, 11, 8).to(2011, 12, 30).byWeek().on(DayOfWeek.MONDAY).build();
and you will get a List<Date> of:
Date(2011,11,14)
Date(2011,11,21)
Date(2011,11,28)
Date(2011,12,5)
Date(2011,12,12)
Date(2011,12,19)
Date(2011,12,26)
FYI, the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.
Using java.time
The LocalDate class is java.time is akin to the Joda-Time LocalDate. A date-only value, without time-of-day and without time zone. One difference is that java.time eschews constructors for factory methods.
LocalDate start = LocalDate.of( 2011 , 11 , 8 );
LocalDate stop = LocalDate.of( 2012 , 5 , 1 );
Collect the Mondays.
List<LocalDate> mondays = new ArrayList<>();
The TemporalAdjuster interface provides for classes that manipulate date-time values. The TemporalAdjusters class (note the plural name) provides various implementations. We want the nextOrSame and next adjusters, passing the desired DayOfWeek.MONDAY enum object.
LocalDate monday = start.with( TemporalAdjusters.nextOrSame( DayOfWeek.MONDAY ) );
while( monday.isBefore( stop ) ) {
mondays.add( monday );
// Set up the next loop.
monday = monday.plusWeeks( 1 );
}
By the way, usually the wise approach in handling a span of time is Half-Open where the beginning is inclusive while the ending is exclusive. So in the code above we are running up to, but not including, the stop date.
If the ending is inclusive, use the negation of isAfter e.g.
while( !monday.isAfter( stop ) ) {
//...
}
Here, monday is not after stop means it is before or up to stop.
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.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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. Hibernate 5 & JPA 2.2 support java.time.
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 brought 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 (26+) bundle implementations of the java.time classes.
For earlier Android (<26), the process of API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
This code takes to string dates and gives the number of sundays and also all the sunday's dates
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class FindAllSundays {
public static int getNumberofSundays(String d1, String d2) throws Exception { // object
// in
// Date
// form
Date date1 = getDate(d1);
Date date2 = getDate(d2);
Calendar c1 = Calendar.getInstance();
c1.setTime(date1);
Calendar c2 = Calendar.getInstance();
c2.setTime(date2);
int sundays = 0;
while (c2.after(c1)) {
// System.out.println(" came here ");
//checks to see if the day1 ....so on next days are sundays if sunday goes inside to increment the counter
if (c1.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
System.out.println(c1.getTime().toString() + " is a sunday ");
sundays++;
}
c1.add(Calendar.DATE, 1);
}
System.out.println("number of sundays between 2 dates is " + sundays);
return sundays;
}
// converts string to date
public static Date getDate(String s) {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = format.parse(s);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return date;
}
public static void main(String[] arg) throws Exception {
System.out.println(" " + getNumberofSundays("2005-10-07", "2006-10-01"));
}
}
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
public class Get_time {
public ArrayList<LocalDate> getmondays(String s,String e)
{
LocalDate start = LocalDate.parse(s);
LocalDate end = LocalDate.parse(e);
List<LocalDate> totalDates_Mondays = new ArrayList<>();
while (!start.isAfter(end)) {
totalDates_Mondays.add(start);
start = start.plusWeeks(1);
}
return (ArrayList<LocalDate>) totalDates_Mondays;
}
public static void main(String ...s1) {
String mon_start = "1600-08-01";
String mon_end= "2016-12-29";
Get_time t=new Get_time();
System.out.println(t.getmondays(mon_start,mon_end));
}
}
In Java 8 using Stream ,
LocalDate startDate = LocalDate.of(2019, 2, 1);
LocalDate endDate = LocalDate.of(2019, 2, 28);
long numOfDays = ChronoUnit.DAYS.between(startDate, endDate);
List<LocalDate> daysRange = Stream.iterate(startDate, date -> date.plusDays(1)).limit(numOfDays).filter( date -> date.getDayOfWeek()==DayOfWeek.MONDAY ).collect(Collectors.toList());
Related
This question already has answers here:
How do I check if a date is within a certain range?
(17 answers)
Closed 5 years ago.
How do I compare dates in between in Java?
Example:
date1 is 22-02-2010
date2 is 07-04-2010 today
date3 is 25-12-2010
date3 is always greater than date1 and date2 is always today. How do I verify if today's date is in between date1 and date 3?
Date has before and after methods and can be compared to each other as follows:
if(todayDate.after(historyDate) && todayDate.before(futureDate)) {
// In between
}
For an inclusive comparison:
if(!historyDate.after(todayDate) && !futureDate.before(todayDate)) {
/* historyDate <= todayDate <= futureDate */
}
You could also give Joda-Time a go, but note that:
Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time (JSR-310).
Back-ports are available for Java 6 and 7 as well as Android.
Use compareTo:
date1.compareTo(date2);
Following are most common way of comparing dates (my preference is Approach 1):
Approach 1: Using Date.before(), Date.after() and Date.equals()
if (date1.after(date2)) {
System.out.println("Date1 is after Date2");
}
if (date1.before(date2)) {
System.out.println("Date1 is before Date2");
}
if (date1.equals(date2)) {
System.out.println("Date1 is equal Date2");
}
Approach 2: Date.compareTo()
if (date1.compareTo(date2) > 0) {
System.out.println("Date1 is after Date2");
} else if (date1.compareTo(date2) < 0) {
System.out.println("Date1 is before Date2");
} else {
System.out.println("Date1 is equal to Date2");
}
Approach 3: Calender.before(), Calender.after() and Calender.equals()
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
if (cal1.after(cal2)) {
System.out.println("Date1 is after Date2");
}
if (cal1.before(cal2)) {
System.out.println("Date1 is before Date2");
}
if (cal1.equals(cal2)) {
System.out.println("Date1 is equal Date2");
}
tl;dr
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) ) ;
Boolean isBetween =
( ! today.isBefore( localDate1 ) ) // “not-before” is short for “is-equal-to or later-than”.
&&
today.isBefore( localDate3 ) ;
Or, better, if you add the ThreeTen-Extra library to your project.
LocalDateRange.of(
LocalDate.of( … ) ,
LocalDate.of( … )
).contains(
LocalDate.now()
)
Half-open approach, where beginning is inclusive while ending is exclusive.
Bad Choice of Format
By the way, that is a bad choice of format for a text representation of a date or date-time value. Whenever possible, stick with the standard ISO 8601 formats. ISO 8601 formats are unambiguous, understandable across human cultures, and are easy to parse by machine.
For a date-only value, the standard format is YYYY-MM-DD. Note how this format has the benefit of being chronological when sorted alphabetically.
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.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
DateTimeFormatter
As your input strings are non-standard format, we must define a formatting pattern to match.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" );
Use that to parse the input strings.
LocalDate start = LocalDate.parse( "22-02-2010" , f );
LocalDate stop = LocalDate.parse( "25-12-2010" , f );
In date-time work, usually best to define a span of time by the Half-Open approach where the beginning is inclusive while the ending is exclusive. So we want to know if today is the same or later than the start and also before the stop. A briefer way of saying “is the same or later than the start” is “not before the start”.
Boolean intervalContainsToday = ( ! today.isBefore( start ) ) && today.isBefore( stop ) ;
See the Answer by gstackoverflow showing the list of comparison methods you can call.
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.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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. Hibernate 5 & JPA 2.2 support java.time.
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 brought 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 (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. 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.
UPDATE: This “Joda-Time” section below is left intact as history. The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
Joda-Time
Other answers are correct with regard to the bundled java.util.Date and java.util.Calendar classes. But those classes are notoriously troublesome. So here's some example code using the Joda-Time 2.3 library.
If you truly want a date without any time portion and no time zone, then use the LocalDate class in Joda-Time. That class provides methods of comparison including compareTo (used with Java Comparators), isBefore, isAfter, and isEqual.
Inputs…
String string1 = "22-02-2010";
String string2 = "07-04-2010";
String string3 = "25-12-2010";
Define a formatter describing the input strings…
DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd-MM-yyyy" );
Use formatter to parse the strings into LocalDate objects…
LocalDate localDate1 = formatter.parseLocalDate( string1 );
LocalDate localDate2 = formatter.parseLocalDate( string2 );
LocalDate localDate3 = formatter.parseLocalDate( string3 );
boolean is1After2 = localDate1.isAfter( localDate2 );
boolean is2Before3 = localDate2.isBefore( localDate3 );
Dump to console…
System.out.println( "Dates: " + localDate1 + " " + localDate2 + " " + localDate3 );
System.out.println( "is1After2 " + is1After2 );
System.out.println( "is2Before3 " + is2Before3 );
When run…
Dates: 2010-02-22 2010-04-07 2010-12-25
is1After2 false
is2Before3 true
So see if the second is between the other two (exclusively, meaning not equal to either endpoint)…
boolean is2Between1And3 = ( ( localDate2.isAfter( localDate1 ) ) && ( localDate2.isBefore( localDate3 ) ) );
Working With Spans Of Time
If you are working with spans of time, I suggest exploring in Joda-Time the classes: Duration, Interval, and Period. Methods such as overlap and contains make comparisons easy.
For text representations, look at the ISO 8601 standard’s:
durationFormat: PnYnMnDTnHnMnSExample: P3Y6M4DT12H30M5S(Means “three years, six months, four days, twelve hours, thirty minutes, and five seconds”)
intervalFormat: start/endExample: 2007-03-01T13:00:00Z/2008-05-11T15:30:00Z
Joda-Time classes can work with strings in both those formats, both as input (parsing) and output (generating strings).
Joda-Time performs comparisons using the Half-Open approach where the beginning of the span is inclusive while the ending is exclusive. This approach is a wise one for handling spans of time. Search StackOverflow for more info.
Compare the two dates:
Date today = new Date();
Date myDate = new Date(today.getYear(),today.getMonth()-1,today.getDay());
System.out.println("My Date is"+myDate);
System.out.println("Today Date is"+today);
if (today.compareTo(myDate)<0)
System.out.println("Today Date is Lesser than my Date");
else if (today.compareTo(myDate)>0)
System.out.println("Today Date is Greater than my date");
else
System.out.println("Both Dates are equal");
Update for Java 8 and later
isAfter()
isBefore()
isEqual()
compareTo()
These methods exists in LocalDate, LocalTime, and LocalDateTime classes.
Those classes are built into Java 8 and later. Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
You can use Date.getTime() which:
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
represented by this Date object.
This means you can compare them just like numbers:
if (date1.getTime() <= date.getTime() && date.getTime() <= date2.getTime()) {
/*
* date is between date1 and date2 (both inclusive)
*/
}
/*
* when date1 = 2015-01-01 and date2 = 2015-01-10 then
* returns true for:
* 2015-01-01
* 2015-01-01 00:00:01
* 2015-01-02
* 2015-01-10
* returns false for:
* 2014-12-31 23:59:59
* 2015-01-10 00:00:01
*
* if one or both dates are exclusive then change <= to <
*/
Try this
public static boolean compareDates(String psDate1, String psDate2) throws ParseException{
SimpleDateFormat dateFormat = new SimpleDateFormat ("dd/MM/yyyy");
Date date1 = dateFormat.parse(psDate1);
Date date2 = dateFormat.parse(psDate2);
if(date2.after(date1)) {
return true;
} else {
return false;
}
}
Use getTime() to get the numeric value of the date, and then compare using the returned values.
This code determine today is in some duration.. based on KOREA locale
Calendar cstart = Calendar.getInstance(Locale.KOREA);
cstart.clear();
cstart.set(startyear, startmonth, startday);
Calendar cend = Calendar.getInstance(Locale.KOREA);
cend.clear();
cend.set(endyear, endmonth, endday);
Calendar c = Calendar.getInstance(Locale.KOREA);
if(c.after(cstart) && c.before(cend)) {
// today is in startyear/startmonth/startday ~ endyear/endmonth/endday
}
This method worked for me:
public static String daysBetween(String day1, String day2) {
String daysBetween = "";
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date1 = myFormat.parse(day1);
Date date2 = myFormat.parse(day2);
long diff = date2.getTime() - date1.getTime();
daysBetween = ""+(TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
} catch (ParseException e) {
e.printStackTrace();
}
return daysBetween;
}
In Java how can I add one month to the current date?
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
Java 8
LocalDate futureDate = LocalDate.now().plusMonths(1);
You can make use of apache's commons lang DateUtils helper utility class.
Date newDate = DateUtils.addMonths(new Date(), 1);
You can download commons lang jar at http://commons.apache.org/proper/commons-lang/
tl;dr
LocalDate::plusMonths
Example:
LocalDate.now( )
.plusMonths( 1 );
Better to specify time zone.
LocalDate.now( ZoneId.of( "America/Montreal" )
.plusMonths( 1 );
java.time
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat. The Joda-Time team also advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
Date-only
If you want the date-only, use the LocalDate class.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
today.toString(): 2017-01-23
Add a month.
LocalDate oneMonthLater = today.plusMonths( 1 );
oneMonthLater.toString(): 2017-02-23
Date-time
Perhaps you want a time-of-day along with the date.
First get the current moment in UTC with a resolution of nanoseconds.
Instant instant = Instant.now();
Adding a month means determining dates. And determining dates means applying a time zone. For any given moment, the date varies around the world with a new day dawning earlier to the east. So adjust that Instant into a time zone.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
Now add your month. Let java.time handle Leap month, and the fact that months vary in length.
ZonedDateTime zdtMonthLater = zdt.plusMonths( 1 );
You might want to adjust the time-of-day to the first moment of the day when making this kind of calculation. That first moment is not always 00:00:00.0 so let java.time determine the time-of-day.
ZonedDateTime zdtMonthLaterStartOfDay = zdtMonthLater.toLocalDate().atStartOfDay( zoneId );
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.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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. Hibernate 5 & JPA 2.2 support java.time.
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 brought 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 (26+) bundle implementations of the java.time classes.
For earlier Android (<26), the process of API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
Joda-Time
Update: The Joda-Time project is now in maintenance mode. Its team advises migration to the java.time classes. I am leaving this section intact for posterity.
The Joda-Time library offers a method to add months in a smart way.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime now = DateTime.now( timeZone );
DateTime nextMonth = now.plusMonths( 1 );
You might want to focus on the day by adjust the time-of-day to the first moment of the day.
DateTime nextMonth = now.plusMonths( 1 ).withTimeAtStartOfDay();
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
java.util.Date dt = cal.getTime();
(adapted from Duggu)
public static Date addOneMonth(Date date)
{
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, 1);
return cal.getTime();
}
you can use DateUtils class in org.apache.commons.lang3.time package
DateUtils.addMonths(new Date(),1);
Use calander and try this code.
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
Date nextMonthFirstDay = calendar.getTime();
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Date nextMonthLastDay = calendar.getTime();
public Date addMonths(String dateAsString, int nbMonths) throws ParseException {
String format = "MM/dd/yyyy" ;
SimpleDateFormat sdf = new SimpleDateFormat(format) ;
Date dateAsObj = sdf.parse(dateAsString) ;
Calendar cal = Calendar.getInstance();
cal.setTime(dateAsObj);
cal.add(Calendar.MONTH, nbMonths);
Date dateAsObjAfterAMonth = cal.getTime() ;
System.out.println(sdf.format(dateAsObjAfterAMonth));
return dateAsObjAfterAMonth ;
}`
If you need a one-liner (i.e. for Jasper Reports formula) and don't mind if the adjustment is not exactly one month (i.e "30 days" is enough):
new Date($F{invoicedate}.getTime() + 30L * 24L * 60L * 60L * 1000L)
This method returns the current date plus 1 month.
public Date addOneMonth() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
return cal.getTime();
}`
public Date addMonth(Date inputDate, int monthToAddNumber){
Calendar calendar = Calendar.getInstance();
calendar.setTime(inputDate);
// Add 'monthToAddNumber' months to inputDate
calendar.add(Calendar.MONTH, monthToAddNumber);
return calendar.getTime();
}
then call method:
addMonth(new Date(), 1)
Use the plusMonths() method of the LocalDate class for Java 8 and Higher Versions.
// Add one month to the current local date
LocalDate localDate = LocalDate.now().plusMonths(1);
// Add one month to any local date object
LocalDate localDate = LocalDate.parse("2022-02-14").plusMonths(1); // 2022-03-14
Reference: https://www.javaexercise.com/java/java-add-months-to-date
You can use like this;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String d = "2000-01-30";
Date date= new Date(sdf.parse(d).getTime());
date.setMonth(date.getMonth() + 1);
In order to find the day after one month, it is necessary to look at what day of the month it is today.
So if the day is first day of month run following code
Calendar calendar = Calendar.getInstance();
Calendar calFebruary = Calendar.getInstance();
calFebruary.set(Calendar.MONTH, Calendar.FEBRUARY);
if (calendar.get(Calendar.DAY_OF_MONTH) == 1) {// if first day of month
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
Date nextMonthFirstDay = calendar.getTime();
System.out.println(nextMonthFirstDay);
}
if the day is last day of month, run following codes.
else if ((calendar.getActualMaximum(Calendar.DAY_OF_MONTH) == calendar.get(Calendar.DAY_OF_MONTH))) {// if last day of month
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Date nextMonthLastDay = calendar.getTime();
System.out.println(nextMonthLastDay);
}
if the day is in february run following code
else if (calendar.get(Calendar.MONTH) == Calendar.JANUARY
&& calendar.get(Calendar.DAY_OF_MONTH) > calFebruary.getActualMaximum(Calendar.DAY_OF_MONTH)) {// control of february
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Date nextMonthLastDay = calendar.getTime();
System.out.println(nextMonthLastDay);
}
the following codes are used for other cases.
else { // any day
calendar.add(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Date theNextDate = calendar.getTime();
System.out.println(theNextDate);
}
Date dateAfterOneMonth = new DateTime(System.currentTimeMillis()).plusMonths(1).toDate();
Constants are in Portuguese because yes, but javadoc is understandable enough.
Just call
Calendar cal = Calendar.getInstance();
cal.setTime(yourDate);
DateSumUtil.sumOneMonth(cal);
and that's that. Related code:
package you.project.your_package_utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
public class DateSumUtil {
private static Integer[] meses31 = { 2, 4, 7, 9 };
private static List<Integer> meses31List = Arrays.asList(meses31);
private static SimpleDateFormat s = new SimpleDateFormat("dd/MM/yyyy");
private static final int MES = Calendar.MONTH;
private static final int ANO = Calendar.YEAR;
private static final int DIA = Calendar.DAY_OF_MONTH;
/**
* Receives a date and adds one month. <br />
*
* #param c date to receive an added month, as {#code java.util.Calendar}
* #param dia day of month of the original month
*/
public static void addOneMonth(Calendar c, int dia) throws ParseException {
if (cal.get(MES) == 0) { if (dia < 29) cal.add(MES, 1);
else { if (cal.get(ANO) % 4 == 0) { if (dia < 30) cal.add(MES, 1);
else cal.setTime(s.parse("29/02/" + cal.get(ANO)));
} else { if (dia < 29) cal.add(MES, 1);
else cal.setTime(s.parse("28/02/" + cal.get(ANO)));
} } } else if (meses31List.contains(cal.get(MES))) {
if (dia < 31) { cal.add(Calendar.MONTH, 1);
cal.set(DIA, dia);
} else cal.setTime(s.parse("30/" + (cal.get(MES) + 2) + "/" + cal.get(ANO)));
} else { cal.add(MES, 1);
cal.set(DIA, dia); }
}
public class StringSplit {
public static void main(String[] args) {
// TODO Auto-generated method stub
date(5, 3);
date(5, 4);
}
public static String date(int month, int week) {
LocalDate futureDate = LocalDate.now().plusMonths(month).plusWeeks(week);
String Fudate = futureDate.toString();
String[] arr = Fudate.split("-", 3);
String a1 = arr[0];
String a2 = arr[1];
String a3 = arr[2];
String date = a3 + "/" + a2 + "/" + a1;
System.out.println(date);
return date;
}
}
Output:
10/03/2020
17/03/2020
I want to get the day of week from the Java Date object when I have an array of Date in String with me.
SimpleDateFormat sourceDateformat = new SimpleDateFormat("yyyy-MM-dd");
public String[] temp_date;
public Int[] day = new Int[5];
Date[] d1= new Date[5];
Calendar[] cal= new Calendar[5]
try {
d1[i]= sourceDateformat.parse(temp_date[i].toString());
cal[i].setTime(d1[i]); // its not compiling this line..showing error on this line
day[i]= cal[i].get(Calendar.DAY_OF_WEEK);
}
catch (ParseException e) {
e.printStackTrace();
}
Does anyone know the answer to this?
You can get the day-integer like that:
Calendar c = Calendar.getInstance();
c.setTime(yourdate); // yourdate is an object of type Date
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); // this will for example return 3 for tuesday
If you need the output to be "Tue" rather than 3, instead of going through a calendar, just reformat the string: new SimpleDateFormat("EE").format(date) (EE meaning "day of week, short version")
Taken from here: How to determine day of week by passing specific date?
// kotlin
val calendar = Calendar.getInstance()
val dateInfo = DateFormat.getDateInstance(DateFormat.FULL).format(calendar.time)
data.text = dateInfo
java.time
You can do it using DateTimeFormatter.ofPattern("EEEE"):
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String args[]) {
// Test
System.out.println(getWeekDayName("2021-04-30"));
}
public static String getWeekDayName(String s) {
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("u-M-d", Locale.ENGLISH);
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("EEEE", Locale.ENGLISH);
return LocalDate.parse(s, dtfInput).format(dtfOutput);
}
}
Output:
Friday
Alternatively, you can get it using LocalDate#getDayOfWeek:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.Locale;
public class Main {
public static void main(String args[]) {
// Test
System.out.println(getWeekDayName("2021-04-30"));
}
public static String getWeekDayName(String s) {
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("u-M-d", Locale.ENGLISH);
return LocalDate.parse(s, dtfInput).getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.ENGLISH);
}
}
Output:
Friday
Learn more about the the modern date-time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
This is one of the many things that have become a lot easier with the advent of java.time, the modern Java date and time API.
String tempDate = "2020-03-29";
LocalDate date = LocalDate.parse(tempDate);
DayOfWeek day = date.getDayOfWeek();
System.out.println(day);
Output:
SUNDAY
Of course we now have got an enum for the days of the week. There’s no longer any reason to fiddle with integers and having to remember on what day of week they begin and whether the days are numbered from 0 or 1.
I am expoiting the fact that your expected input format (yyyy-MM-dd in your code) is ISO 8601, the default for java.time, so we don’t need to specify any formatter explicitly.
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Wikipedia article: ISO 8601
In Kotlin, just do this:
val yourDateStr = "2021-01-01"
val df = DateFormat.parse(yourDateStr)
val weedDay = df.getWeekDay(yourTimeZone)
the below code works, depending on what number you enter in the DAY_OF_WEEK, that returns the specific weekday, in this example it always returns a future date and day will always be Tuesday.
DAY_OF_WEEK
public static String getTodaysDateAndTime(){
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 5);
cal.add(Calendar.DAY_OF_WEEK, 2);
Date date = cal.getTime();
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
String futureDate = dateformat.format(date);
System.out.println(futureDate);
return futureDate;
}
I have two LocalDates that represent some time interval. Now i have to get LocalDates of all fridays, that this interval contains.
Easiest way to do it?
package org.life.java.so.questions;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
/**
*
* #author Jigar
*/
public class JodaTimeDateTraverseQuestion {
public static void main(String[] args) {
DateTime startDt = new DateTime(2010,12,1,0,0,0,0);//1st Dec 2010
DateTime endDt = new DateTime(2010,12,31,0,0,0,0);//31st Dec 2010
DateTime tempDate = new DateTime(startDt.getMillis());
while(tempDate.compareTo(endDt) <=0 ){
if(tempDate.getDayOfWeek() != DateTimeConstants.SATURDAY && tempDate.getDayOfWeek() != DateTimeConstants.SUNDAY){
System.out.println(""+tempDate);
}
tempDate = tempDate.plusDays(1);
}
}
}
Solution: lazily step by one week.
import org.joda.time.LocalDate;
import java.util.Iterator;
public class DayOfWeekIterator implements Iterator<LocalDate>{
private final LocalDate end;
private LocalDate nextDate;
public DayOfWeekIterator(LocalDate start, LocalDate end, int dayOfWeekToIterate){
this.end = end;
nextDate = start.withDayOfWeek(dayOfWeekToIterate);
if (start.getDayOfWeek() > dayOfWeekToIterate) {
nextDate = nextDate.plusWeeks(1);
}
}
public boolean hasNext() {
return !nextDate.isAfter(end);
}
public LocalDate next() {
LocalDate result = nextDate;
nextDate = nextDate.plusWeeks(1);
return result;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
Test
import org.joda.time.DateTimeConstants;
import org.joda.time.LocalDate;
public class DayOfWeekIteratorTest {
public static void main(String[] args) {
LocalDate startDate = new LocalDate(2010, 12, 1);//1st Dec 2010
LocalDate endDate = new LocalDate(2010, 12, 31);//31st Dec 2010
DayOfWeekIterator it = new DayOfWeekIterator(startDate, endDate, DateTimeConstants.FRIDAY);
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
tl;dr
java.time.LocalDate.of( 2018 , Month.JANUARY , 23 ) // A date-only class in the modern *java.time* classes that supplant both Joda-Time and the troublesome old date-time classes.
.with(
TemporalAdjusters.next( DayOfWeek.FRIDAY ) // Nifty `TemporalAdjuster` implementation for moving to another date. Immutable Objects pattern means a new object is returned based on the original which remains unmodified.
)
.isBefore( // Compare `LocalDate` objects with `isBefore`, `isAfter`, and `isEqual`.
LocalDate.of( 2018 , Month.FEBRUARY , 27 );
)
java.time
FYI, the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.
Define your stop & start LocalDate objects.
LocalDate start = LocalDate.of( 2018 , Month.JANUARY , 23 );
LocalDate stop = LocalDate.of( 2018 , Month.FEBRUARY , 27 );
// TODO: Verify start.isBefore( stop ).
Collect the Friday dates we find. You might optimize a bit by sizing the collection.
// Pre-size the collection.
int initialCapacity = ( int ) ( ChronoUnit.WEEKS.between( start , stop ) + 2 ); // Adding two for good measure.
List < LocalDate > fridays = new ArrayList <>( initialCapacity );
Determine the first Friday, using the start date if it is itself a Friday. Use a pair of TemporalAdjuster implementations offered in the TemporalAdjusters class: next(DayOfWeek) & nextOrSame(DayOfWeek). Pass the desired day-of-week via the DayOfWeek enum, seven pre-defined objects, one for each day of the week Monday-Sunday.
LocalDate friday = start.with( TemporalAdjusters.nextOrSame( DayOfWeek.FRIDAY ) );
while ( friday.isBefore( stop ) )
{
fridays.add( friday ); // Remember this Friday date.
// Setup next loop.
friday = friday.with( TemporalAdjusters.next( DayOfWeek.FRIDAY ) );
}
System.out.println( "From " + start + " to " + stop + " = " + fridays );
From 2018-01-23 to 2018-02-27 = [2018-01-26, 2018-02-02, 2018-02-09, 2018-02-16, 2018-02-23]
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, 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, 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.
I'm trying to create number of Evenement instances and set the date for them:
for (int i=2004; i<2009; i++){
evenementen.add(new Evenement("Rock Werchter", "Rock", "Werchter", 200000,
(Date)formatter.parse(i+"/07/03")));
But I can't seem to get it to work,
Any ideas?
You may want to use Calendar to create your dates.
for (int i=2004; i<2009; i++) {
Calendar cal = Calendar.getInstance();
cal.clear();
// Calendar.JULY may be different depending on the JDK language
cal.set(i, Calendar.JULY, 3); // Alternatively, cal.set(i, 6, 3);
evenementen.add(new Evenement("Rock Werchter", "Rock", "Werchter", 200000,
cal.getTime()));
}
Note that the months are zero-based, so July is 6.
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Solution using java.time, the modern API:
import java.time.LocalDate;
import java.time.Month;
public class Main {
public static void main(String[] args) {
for (int i = 2004; i < 2009; i++) {
System.out.println(LocalDate.of(i, Month.JULY, 3));
}
}
}
If you want to do it by parsing the string (the way you have posted in the question), use DateTimeFormatter.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("u/M/d", Locale.ENGLISH);
for (int i = 2004; i < 2009; i++) {
LocalDate date = LocalDate.parse(i + "/07/03", dtf);
System.out.println(date);
}
}
}
Output:
2004-07-03
2005-07-03
2006-07-03
2007-07-03
2008-07-03
Learn more about java.time, the modern Date-Time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Beware of the locale used for the date formatter (default can be Locale.ENGLISH is your OS is set that way, meaning the year is at the end, not at the beginning of the string)
You need to be sure to have a formatter build as (at the time of writing, 2008, Java6, as in this answer):
formatter = new SimpleDateFormat("yyyy/MM/DD");