Getting dates after certain period of time in Java - java

Basically I have a date stored as text in this format: 16/09/2014 in SQLite Browser. I wonder is there any way to get the date after one day, one week, one month and one year of each records in the database using Java.
I retrieved and display the date retrieved from database in a listview:
viewHolder.txt_ddate.setText("Next Payment On: "
+ _recurlist.get(position).getRecurringStartDate().trim());
So I was thinking to use Java technique to get the dates I mentioned above. I have researched on this and found Documentation but I not sure how to implement it into my problem.
Any guides? Thanks in advance.

Use a Calendar object like in your example, which provides the add method.
String dateAsString = "16/09/2014";
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
c.setTime(formatter.parse(dateAsString));
c.add(Calendar.DAY_OF_MONTH, 1);
System.out.println("After one day: " + formatter.format(c.getTimeInMillis()));
c.add(Calendar.DAY_OF_MONTH, -1);
c.add(Calendar.WEEK_OF_YEAR, 1);
System.out.println("After one week: " + formatter.format(c.getTimeInMillis()));
c.add(Calendar.WEEK_OF_YEAR, -1);
c.add(Calendar.MONTH, 1);
System.out.println("After one month: " + formatter.format(c.getTimeInMillis()));
c.add(Calendar.MONTH, -1);
c.add(Calendar.YEAR, 1);
System.out.println("After one year: " + formatter.format(c.getTimeInMillis()));
c.add(Calendar.YEAR, -1);
Output:
After one day: 17/09/2014
After one week: 23/09/2014
After one month: 16/10/2014
After one year: 16/09/2015

With Joda-time:
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy");
LocalDate date = LocalDate.parse("16/09/2014", formatter);
System.out.println(date.toString(formatter));
System.out.println(date.plusDays(1).toString(formatter));
System.out.println(date.plusWeeks(1).toString(formatter));
System.out.println(date.plusMonths(1).toString(formatter));
System.out.println(date.plusYears(1).toString(formatter));
Output:
16/09/2014
17/09/2014
23/09/2014
16/10/2014
16/09/2015

Use Calendar api of Java/Android as follow:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date;
try {
date = sdf.parse(dateStr);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, 1); //add one day to your date
cal.add(Calendar.MONTH, 1); //add 1 month to your date
cal.add(Calendar.YEAR, 1); //add 1 year to current date
System.out.println(sdf.format(cal.getTimeInMillis()));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Here is the example:
String strDate = "16/09/2014";
int noOfDays = 1;
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = formatter.parse(strDate);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, noOfDays);

tl;dr
LocalDate.parse(
"16/09/2014" ,
DateTimeFormatter.ofPattern( "dd/MM/uuuu" )
)
.plusDays( 1 )
.format( DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) )
Details
Tip: Use date-time data types for date-time values. You should be using a date-oriented type to define your column in your database to store a date value rather than as text.
Tip # 2: When you do serialize a date value to text, use the standard ISO 8601 formats. These are sensible, practical, and sort chronologically when alphabetical.
Use the java.time classes rather than the troublesome old date-time classes that are now legacy. For Android, see bullets below.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
LocalDate ld = LocalDate.parse( "16/09/2014" , f ) ;
LocalDate dayAfter = ld.plusDays( 1 ) ;
LocalDate weekAfter = ld.plusWeeks( 1 ) ;
LocalDate monthAfter = ld.plusMonths( 1 ) ;
LocalDate yearAfter = ld.plusYears( 1 ) ;
To generate a string in standard format, simply call toString.
String output = dayAfter.toString() ; // YYYY-MM-DD standard format.
2014-09-17
For other formats, use a DateTimeFormatter as seen above.
String output = dayAfter.format( f ) ;
17/09/2014
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.
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
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….

Related

Issue with Calendar calculation that spans 2 calendar years

I'm using a method that calculates the next Monday from a given date string.
public static String getStartOfNextWeek(String DATE){
String format = "dd.MM.yyyy";SimpleDateFormat df = new SimpleDateFormat(format);
Date date = null;
try {
date = df.parse(DATE);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week = cal.get(Calendar.WEEK_OF_YEAR);
int year = cal.get(Calendar.YEAR);
Calendar calendar = new GregorianCalendar();
calendar.clear();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.WEEK_OF_YEAR, week);
//add 8 days to get next weeks Monday
calendar.add(Calendar.DAY_OF_WEEK, 8);
Date startDate = calendar.getTime();
SimpleDateFormat df2 = new SimpleDateFormat("dd.MM.yyyy");
String start = df2.format(startDate);
return start;
This work perfectly fine over a single calendar year, but when I'm passing a value that spans two calendar years problems arise.
For example:
input: 15.12.2014
output: 22.12.2014 CORRECT
input: 22.12.2014
output: 29.12.2014 CORRECT
input: 29.12.2014
output: 6.1.2014 INCORRECT
I realize where the mistake is located, since it takes WEEK_OF_YEAR as "1", but YEAR as "2014", so the output is technically correct. Just wrong for my purpose.
How would i best tell the calendar object that i want the next monday in week 1, but 2015?
UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. This Answer is left intact as history. See my newer Answer.
Joda-Time
The Joda-Time library, version 2.5, gets the correct answer. And gets it more easily.
// Parse input string.
String input = "29.12.2014";
DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd.MM.yyyy" );
LocalDate inputLocalDate = formatter.parseLocalDate( input );
// Find desired Monday.
LocalDate possibleMonday = inputLocalDate.withDayOfWeek( DateTimeConstants.MONDAY );
// The possible Monday could be past, present, or future of our input date. Adjust as needed.
LocalDate desiredMonday = null;
if ( possibleMonday.isBefore( inputLocalDate ) || possibleMonday.isEqual( inputLocalDate ) ) {
desiredMonday = possibleMonday.plusWeeks( 1 ); // If the possible Monday is past or present, add a week to get *next* Monday.
} else {
desiredMonday = possibleMonday; // If the possible Monday is future, use it.
}
String output = formatter.print( desiredMonday );
Dump to console.
System.out.println( "input : " + input );
System.out.println( "inputLocalDate : " + inputLocalDate );
System.out.println( "desiredMonday : " + desiredMonday );
System.out.println( "output : " + output );
When run.
input : 29.12.2014
inputLocalDate : 2014-12-29
desiredMonday : 2015-01-05
output : 05.01.2015
There's something weird when combining Date and Calender, when it comes to parsing dates, using only Calender it works great;
String[] dt = dateStr.split("\\.");
GregorianCalendar cal = new GregorianCalendar(Integer.parseInt(dt[2]), (Integer.parseInt(dt[1])-1), Integer.parseInt(dt[0]));
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.clear(Calendar.DAY_OF_WEEK);
cal.add(Calendar.DATE, 7);
System.out.println(cal.get(Calendar.YEAR) + "." + (cal.get(Calendar.MONTH)+1) + "." + cal.get(Calendar.DATE));
Edit: You have to subtract 1 from the month, since calendar expects the months to range from 0 to 11.
(Calendar.JANUARY == 0) //true
tl;dr
LocalDate.parse(
"29.12.2014" ,
DateTimeFormatter.ofPattern( "dd.MM.uuuu" )
).with(
TemporalAdjusters.next( DayOfWeek.MONDAY )
)
2015-01-05
java.time
The modern approach uses the java.time classes.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd.MM.uuuu" )
LocalDate ld = LocalDate.parse( "29.12.2014" , f ) ;
To move to another date, use a TemporalAdjuster implementation found in the TemporalAdjusters class. Specify the desired day-of-week with DayOfWeek enum object. No problem crossing end-of-year/start-of-year.
LocalDate followingMonday = ld.with( TemporalAdjusters.next( DayOfWeek.MONDAY ) ) ;
If you want to use the current date if it is a Monday, use TemporalAdjusters.nextOrSame.
Similar methods provide for previous day-of-week, as well: previous & previousOrSame.
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.
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.

How to get next month start date and end date if current month is february? [duplicate]

This question already has answers here:
How to get the first date and last date of the previous month? (Java)
(9 answers)
Closed 4 years ago.
String febSt = "02/01/2014" ;
String febEnd = "02/28/2014" ;
Above code is my input i need "03/01/2014" and "03/31/2014" as output .
I tried more codes and used calendar functions also but no result.From this program i need next month start and end date .
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class MonthCalculation {
public void getNextMonth(String date) throws ParseException{
DateFormat format = new SimpleDateFormat("MM/dd/yyyy");
Date dt = format.parse(date);
Date begining, end;
{
Calendar calendar = getCalendarForNow(dt);
calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
setTimeToEndofDay(calendar);
end = calendar.getTime();
SimpleDateFormat endDt = new SimpleDateFormat("MM/dd/yyyy");
String endStrDt = endDt.format(end);
if(date != null && date.equalsIgnoreCase(endStrDt)){
System.out.println("Ending of the month");
calendar.add(Calendar.DAY_OF_MONTH, 1);
Date lastDate = calendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
String lastDateofNextMonth = sdf.format(lastDate);
System.out.println("Next Month :"+lastDateofNextMonth);
Calendar c = getCalendarForNow(new Date(lastDateofNextMonth));
calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
setTimeToEndofDay(calendar);
end = calendar.getTime();
SimpleDateFormat sfd = new SimpleDateFormat("MM/dd/yyyy");
String lastDated = endDt.format(end);
System.out.println("Testing side :"+lastDated);
}else if (findLeapYear(dt)){
Calendar calendar3 = getCalendarForNow(dt);
calendar3.add(Calendar.YEAR, 1);
Date ds = calendar3.getTime();
SimpleDateFormat dtft = new SimpleDateFormat("MM/dd/yyyy");
String dates = dtft.format(ds);
dtft.setLenient(false);
System.out.println("YEAR : "+dates);
}else{
SimpleDateFormat dtft = new SimpleDateFormat("MM/dd/yyyy");
Calendar calendar2 = getCalendarForNow(dt);
System.out.println(" Calendar time :->> " + dtft.format(calendar2.getTime()));
int curre_month = calendar2.get(Calendar.MONTH);
int curre_day = calendar2.get(Calendar.DAY_OF_MONTH);
int curre_year = calendar2.get(Calendar.YEAR);
Date dat = calendar2.getTime();
calendar2.add(Calendar.DATE, 31);
Date ds = calendar2.getTime();
String dates = dtft.format(ds);
dtft.setLenient(false);
System.out.println("OTHER DAYS : "+dates);
}
}
}
private static boolean findLeapYear(Date dt){
boolean isLeapYr = false;
int yr = dt.getYear();
if ((yr%4 == 0 && yr%100!=0)){
isLeapYr = true;
}
return isLeapYr;
}
private static Calendar getCalendarForNow(Date dt) {
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTime(dt);
return calendar;
}
private static void setTimeToBeginningOfDay(Calendar calendar) {
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.DAY_OF_MONTH, 1);
}
private static void setTimeToEndofDay(Calendar calendar) {
System.out.println("For feb calling");
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
}
public static void main(String[] args) {
try {
String janSt = "01/01/2014" ;
String janEnd = "01/31/2014" ;
String febSt = "02/01/2014" ;
String febEnd = "02/28/2014" ;
String marSt = "03/01/2014" ;
String marEnd = "03/31/2014" ;
String aprilSt = "04/01/2014" ;
String aprilEnd = "04/30/2014" ;
String maySt = "05/01/2014" ;
String mayEnd = "05/31/2014" ;
String juneSt = "06/01/2014" ;
String juneEnd = "06/30/2014" ;
String julySt = "07/01/2014" ;
String julyEnd = "07/31/2014" ;
String augSt = "08/01/2014" ;
String augEnd = "08/31/2014" ;
String sepSt = "09/01/2014" ;
String sepEnd = "09/30/2014" ;
String octSt = "10/01/2014" ;
String octEnd = "10/31/2014" ;
String novSt = "11/01/2014" ;
String novEnd = "11/30/2014" ;
String deceSt = "12/01/2014" ;
String deceEnd = "12/31/2014" ;
String jan15St="01/01/2015";
String jan15End="01/31/2015";
String leapyr = "02/29/2016";
String notaleapyr = "02/28/2015";
new MonthCalculation().getNextMonth(febSt);
} catch (ParseException e) {
e.printStackTrace();
}
}
I tried more with sample inputs , for the months February ,april, june nov start date are not working if i pass these dates as inputs it returns with 2nd of next month
Suggest any idea to proceed further.I am struggling this code.
Thanks in advance
Try this:
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();
tl;dr
LocalDate.parse( "02/14/2014" , DateTimeformatter.ofPattern( "MM/dd/uuuu" ) )
.with( TemporalAdjusters.firstDayOfNextMonth() )
…and…
LocalDate.parse( "02/14/2014" , DateTimeformatter.ofPattern( "MM/dd/uuuu" ) )
.with( TemporalAdjusters.lastDayOfMonth() )
java.time
The modern way is with the new java.time package bundled with Java 8 (inspired by Joda-Time, defined by JSR 310).
The LocalDate class represents a date-only value without time-of-day and without time zone.
DateTimeFormatter f = DateTimeformatter.ofPattern( "MM/dd/uuuu" );
LocalDate ld = LocalDate.parse( "02/14/2014" , f );
The TemporalAdjuster interface defines a way for implementations to manipulate date-time values. The TemporalAdjusters class provides several handy implementations.
LocalDate firstOfMonth = ld.with( TemporalAdjusters.firstDayOfMonth() );
LocalDate firstOfNextMonth = ld.with( TemporalAdjusters.firstDayOfNextMonth() );
The Question asks for the first and last of the following month, March in this case. We have the first of next month, so we just need the end of that month.
LocalDate lastOfNextMonth = firstOfNextMonth.with( TemporalAdjusters.lastDayOfMonth() );
By the way, as discussed below, the best practice for defining a span of time is the Half-Open approach. That means a month is the first of the month and running up to, but not including, the first of the month after. In this approach we do not bother with determining the last day of the month.
Joda-Time
UPDATE: The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
Easy when using the Joda-Time library and its LocalDate class.
DateTimeFormatter formatter = DateTimeFormat.forPattern( "MM/dd/yyyy" );
LocalDate localDate = formatter.parseLocalDate( "02/14/2014" );
LocalDate firstOfMonth = localDate.withDayOfMonth( 1 );
LocalDate nextMonth = localDate.plusMonths(1); // Use this for "half-open" range.
LocalDate endOfMonth = nextMonth.minusDays(1); // Use this for "fully-closed" range.
Half-Open
Tip: Rather than focus on the last moment of a span of time, a better practice is to use the "Half-Open" approach.
In half-open, the beginning is inclusive and the ending is exclusive. So for "a month", we start with the first of the desired month and run up to, but not including, the first of the next month.
February 2014 = 2014-02-01/2014-03-01
Span Of Time
Be aware that Joda-Time provides three handy classes for handling a span of time: Interval, Period, and Duration.
These classes work only with date-time objects (DateTime class) rather than the date-only (LocalDate class) shown in code above.
While not directly relevant to your question, I suspect these span-of-time classes may be helpful.
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.
Something I quickly wrote for you - so could be cleaned up. Check if this helps:
String string = "02/01/2014"; //assuming input
DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date dt = sdf .parse(string);
Calendar c = Calendar.getInstance();
c.setTime(dt);
c.add(Calendar.MONTH, 1); //adding a month directly - gives the start of next month.
String firstDate = sdf.format(c.getTime());
System.out.println(firstDate);
//get last day of the month - add month, substract a day.
c.add(Calendar.MONTH, 1);
c.add(Calendar.DAY_OF_MONTH, -1);
String lastDate = sdf.format(c.getTime());
System.out.println(lastDate);
since it is hard to get in your code I have write some coe for you. please check it out..
Date today = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(today);
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.DATE, -1);
Date lastDayOfMonth = calendar.getTime();
DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
System.out.println("Today : " + sdf.format(today));
System.out.println("Last Day of Month: " + sdf.format(lastDayOfMonth));
I see the question is old. But I used the DateUtils static methods ceiling and truncate. Came in pretty handy instead of using multiple lines of code.
Date today = new Date();
DateUtils.truncate(new Date(), Calendar.MONTH) // Thu Dec 01 00:00:00 EET 2016
DateUtils.ceiling(new Date(), Calendar.MONTH) // Sun Jan 01 00:00:00 EET 2017

Get the last day of next three weeks Java

I want to get the last day of next three weeks.
For example,if today is Wednesday,16 April ,I will get the result Sunday,4 May.
I have written a function like this
public static Date nexThreeWeekEnd() {
Date now = new Date();
Date nextWeeks = DateUtils.truncate(DateUtils.addWeeks(now, 3), Calendar.DATE);
Calendar calendar = Calendar.getInstance();
calendar.setTime(nextWeeks);
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_WEEK));
return calendar.getTime();
}
DateUtils is used from this library:
org.apache.commons.lang.time.DateUtils;
But this function will return Wednesday, 7 May, that's mean it will return exactly the day of current date.
It's not necessary to rewrite my function. Any other ways to solve my problem will be very appriciated.
Thanks.
Use below code hope it helps
Calendar cal = Calendar.getInstance();
int currentDay = cal.get(Calendar.DAY_OF_WEEK);
int leftDays= Calendar.SUNDAY - currentDay;
cal.add(Calendar.DATE, leftDays)
Just try with:
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
c.add(Calendar.WEEK_OF_YEAR, 2);
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
System.out.println(df.format(c.getTime()));
Output:
2014/05/04
You can do something like this:
Calendar calendar = Calendar.getInstance().getFirstDayOfWeek();
calendar.add(Calendar.WEEK_OF_YEAR, 4);
calendar.add(Calendar.DAY_OF_MONTH, -1);
IN Java we can make use of Gregorian calendar
please check if below code helps you
Date d = new Date();
GregorianCalendar cal1 = new GregorianCalendar();
cal1.setTime(d);
System.out.println(cal1.getTime());
int day = cal1.get(Calendar.DAY_OF_WEEK );
cal1.add(Calendar.DAY_OF_YEAR,-(day-1));/*go to start of the week*/
cal1.add(Calendar.WEEK_OF_YEAR,3); // add 3 weeks
day = cal1.get(Calendar.DAY_OF_MONTH );// get the end Day of the 3rd week
System.out.println("end of the 3rd week ="+day);
The Question and other Answers use old outmoded classes.
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. See Oracle Tutorial. Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
The LocalDate class represents a date-only value without time-of-day and time zone. You can use a TemporalAdjuster to generate a new LocalDate value relative to the original. The TemporalAdjusters (note the plural) class implements several handy such adjusters includning the one we need, nextOrSame( WeekOfDay ). The WeekOfDay class is a handy enum representing each of the seven days of the week, Monday-Sunday.
LocalDate start = LocalDate.of ( 2014 , Month.APRIL , 16 );
LocalDate nextOrSameSunday = start.with ( TemporalAdjusters.nextOrSame ( DayOfWeek.SUNDAY ) );
LocalDate twoWeeksAfterNextOrSameSunday = nextOrSameSunday.plusWeeks ( 2 );
Dump to console.
System.out.println ( "start: " + start + " | nextOrSameSunday: " + nextOrSameSunday + " | twoWeeksAfterNextOrSameSunday: " + twoWeeksAfterNextOrSameSunday );
start: 2014-04-16 | nextOrSameSunday: 2014-04-20 | twoWeeksAfterNextOrSameSunday: 2014-05-04

how to check if one date is after another in java?

I am taking in two dates as command line arguments and want to check if the first one is after the second date. the format of the date it "dd/MM/yyy".
Example: java dateCheck 01/01/2014 15/03/2014
also i will need to check if a third date hardcoded into the program is before the second date.
try {
System.out.println("Enter first date : (dd/MM/yyyy)");
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = sdf.parse(bufferRead.readLine());
System.out.println("Enter second date : (dd/MM/yyyy)");
Date date2 = sdf.parse(bufferRead.readLine());
System.out.println(date1 + "\n" + date2);
if (date1.after(date2)) {
System.out.println("Date1 is after Date2");
} else {
System.out.println("Date2 is after Date1");
}
} catch (IOException e) {
e.printStackTrace();
}
To compare two dates :
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyy");
Date firstDate = sdf.parse("01/01/2014");
Date secondDate = sdf.parse("15/03/2014");
if(firstDate.before(secondDate)){
System.out.println("firstDate < secondDate");
}
else if(firstDate.after(secondDate)){
System.out.println("firstDate > secondDate");
}
else if(firstDate.equals(secondDate)){
System.out.println("firstDate = secondDate");
}
tl;dr
LocalDate ld1 = LocalDate.parse( "01/01/2014" , DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ) ;
LocalDate ld2 = LocalDate.parse( "15/03/2014" , DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ) ;
LocalDate ld3 = LocalDate.of( 2014 , Month.JULY , 1 ) ;
Boolean isFirstDateBeforeSecondDate = ld1.isBefore( ld2 ) ;
Boolean isThirdDateBeforeSecondDate = ld3.isBefore( ld2 ) ;
Boolean result = ( isFirstDateBeforeSecondDate && isThirdDateBeforeSecondDate ) ;
return result ;
Using java.time
The modern approach uses the java.time classes rather than the troublesome old legacy date-time classes (Date, Calendar, etc.).
The LocalDate class represents a date-only value without time-of-day and without time zone.
Define a formatting pattern to match your input strings using the DateTimeFormatter class.
String input = "15/03/2014" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate ld = LocalDate.parse( input , f );
ld.toString(): 2014-03-15
To specify a fixed date, pass year, month, and dayOfMonth. For the month, you may specify a number, sanely numbered 1-12 for January-December (unlike the crazy 0-11 in the legacy classes!). Or you may choose to use the Month enum objects.
LocalDate firstOf2014 = LocalDate.of( 2014 , Month.JANUARY , 1 );
Compare using isBefore, isEqual, or isAfter methods.
Boolean isInputDateBeforeFixedDate = ld.isBefore( firstOf2014 ) ;
isInputDateBeforeFixedDate.toString(): false
ISO 8601
If possible, replace your particular date string format with the standard ISO 8601 format. That standard defines many useful practical unambiguous string formats for date-time values.
The java.time classes use the standard formats by default when parsing/generating strings. You can see examples in the code above. For a date-only value, the standard format is YYYY-MM-DD.
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.
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
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
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.
Use SimpleDateFormat to convert a string to Date.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = sdf.parse("01/01/2017");
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 */
}
To read a date and check before:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyy");
try {
Date date1 = sdf.parse(string1);
Date date2 = sdf.parse(string2);
if(date1.before(date2)) {
// do something
}
} catch(ParseException e) {
// the format of the read dates is not the expected one
}

Retrieve current week's Monday's date

We have a utility that will run any day between Monday - Friday. It will update some number of files inside a Content Management Tool. The last modified date associated with that file should be, that week's monday's date. I wrote the following program to retrieve current week's monday's date. But I am still not sure whether this would work for all scenarios. Has anyone got a better solution ?
Calendar c = Calendar.getInstance();
c.setTime(new Date());
System.out.println(c.get(Calendar.DAY_OF_MONTH));
System.out.println(c.get(Calendar.DAY_OF_WEEK));
int mondayNo = c.get(Calendar.DAY_OF_MONTH)-c.get(Calendar.DAY_OF_WEEK)+2;
c.set(Calendar.DAY_OF_MONTH,mondayNo);
System.out.println("Date "+c.getTime());
I would strongly recommend using Joda Time instead (for all your date/time work, not just this):
// TODO: Consider time zones, calendars etc
LocalDate now = new LocalDate();
LocalDate monday = now.withDayOfWeek(DateTimeConstants.MONDAY);
System.out.println(monday);
Note that as you've used Monday here, which is the first day of the week in Joda Time, this will always return an earlier day (or the same day). If you chosen Wednesday (for example), then it would advance to Wednesday from Monday or Tuesday. You can always add or subtract a week if you need "the next Wednesday" or "the previous Wednesday".
EDIT: If you really want to use java.util.Date/Calendar, you can use:
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Date " + c.getTime());
You can use Calendar.setFirstDayOfWeek to indicate whether a week is Monday-Sunday or Sunday-Saturday; I believe setting the day of the week will stay within the current week - but test it.
tl;dr
LocalDate previousMonday =
LocalDate.now( ZoneId.of( "America/Montreal" ) )
.with( TemporalAdjusters.previous( DayOfWeek.MONDAY ) );
java.time
Both the java.util.Calendar class and the Joda-Time library have been supplanted by the java.time framework built into Java 8 and later. See Oracle Tutorial. Much of the java.time functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP. With modern Android tooling and its "API desugaring", you need not add any library.
The java.time.LocalDate class represents a date-only value without time-of-day and without time zone.
Determining today's date requires a time zone, a ZoneId.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zoneId );
The TemporalAdjuster interface (see Tutorial) is a powerful but simple way to manipulate date-time values. The TemporalAdjusters class (note the plural) implements some very useful adjustments. Here we use previous( DayOfWeek).
The handy DayOfWeek enum makes it easy to specify a day-of-week.
LocalDate previousMonday = today.with( TemporalAdjusters.previous( DayOfWeek.MONDAY ) );
If today is Monday, and you want to use today rather than a week ago, call previousOrSame.
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….
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.
The following will work, including wrapping months:
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.setTime(new Date());
int today = c.get(Calendar.DAY_OF_WEEK);
c.add(Calendar.DAY_OF_WEEK, -today+Calendar.MONDAY);
System.out.println("Date "+c.getTime());
If, however, you edit your application on a Sunday (eg. Sunday 12 Feb), the date will be for the following Monday. Based on your requirements (the app will only run Monday thru Friday), this should not pose a problem.
As Jon suggested, the calendar.set method works...
I've tested it both in the case of a monday in same month and in another month using following snippet :
Calendar c = Calendar.getInstance();
//ensure the method works within current month
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Date " + c.getTime());
//go to the 1st week of february, in which monday was in january
c.set(Calendar.DAY_OF_MONTH, 1);
System.out.println("Date " + c.getTime());
//test that setting day_of_week to monday gives a date in january
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Date " + c.getTime());
//same for tuesday
c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
System.out.println("Date " + c.getTime());
The results:
Date Mon Feb 13 10:29:41 CET 2012
Date Wed Feb 01 10:29:41 CET 2012
Date Mon Jan 30 10:29:41 CET 2012
Date Tue Jan 31 10:29:41 CET 2012
What about using Joda Time library... Take look at this answer...
in case you don't want to use Joda Time you can do like this to find the weeks -> (works on Android)
public static ArrayList<String> getWeeks(int month) {
ArrayList<String> arrayListValues = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("MMMM d");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, month);
int day = calendar.get(Calendar.DAY_OF_WEEK);
while (day != 1) {
calendar.add(Calendar.DATE, 1);
day = calendar.get(Calendar.DAY_OF_WEEK);
}
calendar.add(Calendar.DATE, -14);
String y1 = sdf.format(calendar.getTime());
calendar.add(Calendar.DATE, 6);
String y2 = sdf.format(calendar.getTime());
calendar.add(Calendar.DATE, 1);
arrayListValues.add(y1 + " - " + y2);
y1 = sdf.format(calendar.getTime());
calendar.add(Calendar.DATE, 6);
y2 = sdf.format(calendar.getTime());
calendar.add(Calendar.DATE, 1);
arrayListValues.add(y1 + " - " + y2);
for (int i = 0; i < 10; i++) {
y1 = sdf.format(calendar.getTime());
calendar.add(Calendar.DATE, 6);
y2 = sdf.format(calendar.getTime());
calendar.add(Calendar.DATE, 1);
arrayListValues.add(y1 + " - " + y2);
}
return arrayListValues;
}
For version Android 6.0 or grater use:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
int day = 1, month = 7, year = 2018;
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.set(year, month, day);
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); //change de day to monday
String dateMonday= sdf.format(c.getTime());
For version Android 5.1 or less it does not work appropriately, I created my own method.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
int day = 1, month = 7, year = 2018;
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.MONDAY);
//set the date with your date or the current date c.set(new Date());
c.set(year, month, day);
int diaSemana = c.get(Calendar.DAY_OF_WEEK);
for (int i = 0; i < 7; i++) {
if (diaSemana != Calendar.MONDAY) {
day--;
c.set(year, month, day);
diaSemana = c.get(Calendar.DAY_OF_WEEK);
if (diaSemana == Calendar.MONDAY) break;
} else {
break;
}
}
String dateMonday= sdf.format(c.getTime());
Kotlin code. Works in older android versions
val c = Calendar.getInstance()
c.time = Date()
while (c.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
c.add(Calendar.DAY_OF_WEEK, -1)
}
It won't work if the currents week monday is the month before... For example if today is Friday 1st of June... You should probably rather use the roll method...

Categories