Compare two dates in Java - java

I need to compare two dates in java. I am using the code like this:
Date questionDate = question.getStartDate();
Date today = new Date();
if(today.equals(questionDate)){
System.out.println("Both are equals");
}
This is not working. The content of the variables is the following:
questionDate contains 2010-06-30 00:31:40.0
today contains Wed Jun 30 01:41:25 IST 2010
How can I resolve this?

Date equality depends on the two dates being equal to the millisecond. Creating a new Date object using new Date() will never equal a date created in the past. Joda Time's APIs simplify working with dates; however, using the Java's SDK alone:
if (removeTime(questionDate).equals(removeTime(today))
...
public Date removeTime(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}

I would use JodaTime for this. Here is an example - lets say you want to find the difference in days between 2 dates.
DateTime startDate = new DateTime(some_date);
DateTime endDate = new DateTime(); //current date
Days diff = Days.daysBetween(startDate, endDate);
System.out.println(diff.getDays());
JodaTime can be downloaded from here.

It's not clear to me what you want, but I'll mention that the Date class also has a compareTo method, which can be used to determine with one call if two Date objects are equal or (if they aren't equal) which occurs sooner. This allows you to do something like:
switch (today.compareTo(questionDate)) {
case -1: System.out.println("today is sooner than questionDate"); break;
case 0: System.out.println("today and questionDate are equal"); break;
case 1: System.out.println("today is later than questionDate"); break;
default: System.out.println("Invalid results from date comparison"); break;
}
It should be noted that the API docs don't guarantee the results to be -1, 0, and 1, so you may want to use if-elses rather than a switch in any production code. Also, if the second date is null, you'll get a NullPointerException, so wrapping your code in a try-catch may be useful.

The easiest way to compare two dates is converting them to numeric value (like unix timestamp).
You can use Date.getTime() method that return the unix time.
Date questionDate = question.getStartDate();
Date today = new Date();
if((today.getTime() == questionDate.getTime())) {
System.out.println("Both are equals");
}

java.time
In Java 8 there is no need to use Joda-Time as it comes with a similar new API in the java.time package. Use the LocalDate class.
LocalDate date = LocalDate.of(2014, 3, 18);
LocalDate today = LocalDate.now();
Boolean isToday = date.isEqual( today );
You can ask for the span of time between the dates with Period class.
Period difference = Period.between(date, today);
LocalDate is comparable using equals and compareTo as it holds no information about Time and Timezone.
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.

it is esy using time.compareTo(currentTime) < 0
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class MyTimerTask {
static Timer singleTask = new Timer();
#SuppressWarnings("deprecation")
public static void main(String args[]) {
// set download schedule time
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 54);
calendar.set(Calendar.SECOND, 0);
Date time = (Date) calendar.getTime();
// get current time
Date currentTime = new Date();
// if current time> time schedule set for next day
if (time.compareTo(currentTime) < 0) {
time.setDate(time.getDate() + 1);
} else {
// do nothing
}
singleTask.schedule(new TimerTask() {
#Override
public void run() {
System.out.println("timer task is runing");
}
}, time);
}
}

The following will return true if two Calendar variables have the same day of the year.
public boolean isSameDay(Calendar c1, Calendar c2){
final int DAY=1000*60*60*24;
return ((c1.getTimeInMillis()/DAY)==(c2.getTimeInMillis()/DAY));
} // end isSameDay

Here is an another answer:
You need to format the tow dates to fit the same fromat to be able to compare them as string.
Date questionDate = question.getStartDate();
Date today = new Date();
SimpleDateFormat dateFormatter = new SimpleDateFormat ("yyyy/MM/dd");
String questionDateStr = dateFormatter.format(questionDate);
String todayStr = dateFormatter.format(today);
if(questionDateStr.equals(todayStr)) {
System.out.println("Both are equals");
}

public static double periodOfTimeInMillis(Date date1, Date date2) {
return (date2.getTime() - date1.getTime());
}
public static double periodOfTimeInSec(Date date1, Date date2) {
return (date2.getTime() - date1.getTime()) / 1000;
}
public static double periodOfTimeInMin(Date date1, Date date2) {
return (date2.getTime() - date1.getTime()) / (60 * 1000);
}
public static double periodOfTimeInHours(Date date1, Date date2) {
return (date2.getTime() - date1.getTime()) / (60 * 60 * 1000);
}
public static double periodOfTimeInDays(Date date1, Date date2) {
return (date2.getTime() - date1.getTime()) / (24 * 60 * 60 * 1000L);
}

This is a very old post though sharing my work. Here is a little trick to do so
DateTime dtStart = new DateTime(Dateforcomparision);
DateTime dtNow = new DateTime(); //current date
if(dtStart.getMillis() <= dtNow.getMillis())
{
//to do
}
use comparator as per your requirement

in my case, I just had to do something like this :
date1.toString().equals(date2.toString())
And it worked!

It works best....
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
boolean sameDay = cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR);

Here's what you can do for say yyyy-mm-dd comparison:
GregorianCalendar gc= new GregorianCalendar();
gc.setTimeInMillis(System.currentTimeMillis());
gc.roll(GregorianCalendar.DAY_OF_MONTH, true);
Date d1 = new Date();
Date d2 = gc.getTime();
SimpleDateFormat sf= new SimpleDateFormat("yyyy-MM-dd");
if(sf.format(d2).hashCode() < sf.format(d1).hashCode())
{
System.out.println("date 2 is less than date 1");
}
else
{
System.out.println("date 2 is equal or greater than date 1");
}

Related

Retrieving the time between two dates and checking if a month had passed [duplicate]

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

How to compare time string with current time in java?

I have a time string like "15:30" i want to compare that string with the current time.
Please suggest something easy.
And how to get the current time in hour minute format("HH:mm")
tl;dr
LocalTime
.now()
.isAfter(
LocalTime.parse( "15:30" )
)
Details
You should be thinking the other way around: How to get that string turned into a time value. You would not attempt math by turning your numbers into strings. So too with date-time values.
Avoid the old bundled classes, java.util.Date and .Calendar as they are notoriously troublesome, flawed both in design and implementation. They are supplanted by the new java.time package in Java 8. And java.time was inspired by Joda-Time.
Both java.time and Joda-Time offer a class to capture a time-of-day without any date to time zone: LocalTime.
java.time
Using the java.time classes built into Java, specifically LocalTime. Get the current time-of-day in your local time zone. Construct a time-of-day per your input string. Compare with the isBefore, isAfter, or isEqual methods.
LocalTime now = LocalTime.now();
LocalTime limit = LocalTime.parse( "15:30" );
Boolean isLate = now.isAfter( limit );
Better to specify your desired/expected time zone rather than rely implicitly on the JVM’s current default time zone.
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
LocalTime now = LocalTime.now( z ); // Explicitly specify the desired/expected time zone.
LocalTime limit = LocalTime.parse( "15:30" );
Boolean isLate = now.isAfter( limit );
Joda-Time
The code in this case using the Joda-Time library happens to be nearly the same as the code seen above for java.time.
Beware that the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.
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.
Just compare the strings as normal like so:
String currentTime = new SimpleDateFormat("HH:mm").format(new Date());
String timeToCompare = "15:30";
boolean x = currentTime.equals(timeToCompare);
If the times are the same x will be true if they are not x will be false
Following would get the time. You can than use it to compare
String currentTime=new SimpleDateFormat("HH:mm").format(new Date());
I have a similar situation where I need to compare time string like "15:30" with the current time.
I am using Java 7 so I can not use Basil Bourque's solution.
So I have implemented one method which takes one string like "15:30" and
check with current time and returns true if current time is after input time.
public static boolean checkSlaMissedOrNot(String sla) throws ParseException {
boolean slaMissedOrnot = false;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(sla.substring(0, 2)));
cal.set(Calendar.MINUTE, Integer.parseInt(sla.substring(3)));
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
if (Calendar.getInstance().after(cal)) {
System.out.println("it's SLA missed");
slaMissedOrnot = true;
} else {
System.out.println("it's fine & not SLA missed");
}
return slaMissedOrnot;
}
Calendar has other use full methods like after(Object when)
Returns whether this Calendar represents a time after the time represented by the specified Object.
You can use this method also to compare time string with the current time.
So my Solution is a little bit different, Its starts with creating an clock with the current time, and testing the hour agaisnt a user defined int.
public void TextClockWindow() {
this.pack();
javax.swing.Timer t = new javax.swing.Timer(1000, (ActionEvent e) -> {
Calendar calendar = new GregorianCalendar();
String am_pm;
calendar.setTimeZone(TimeZone.getDefault());
Calendar now = Calendar.getInstance();
int h = now.get(Calendar.HOUR_OF_DAY);
int m = now.get(Calendar.MINUTE);
int s = now.get(Calendar.SECOND);
if (calendar.get(Calendar.AM_PM) == 0) {
am_pm = "AM";
} else {
am_pm = "PM";
} // Code to Determine whether the time is AM or PM
Clock.setText("" + h + ":" + m + " " + am_pm);
if(h < 5) { //int here which tests agaisnt the hour evwery second
System.out.println("Success");
} else {
System.out.println("Failure");
}
});
t.start();
}
Try this
public static String compareTime(String d) {
if (null == d)
return "";
try {
SimpleDateFormat sdf= new SimpleDateFormat("HH:mm");
d = sdf.format(new Date());
} catch (Exception e) {
e.printStackTrace();
}
return d;
}
then you can compare with your string
Here is my example to compare before and after current time :
MainActivity.java
Button search = (Button) findViewById(R.id.searchBus);
SimpleDateFormat sdfDate = new SimpleDateFormat("HH:mm");
String limit = "23:00";
Date limitBus=null;
try {
limitBus = sdfDate.parse(limit);
} catch (ParseException e) {
e.printStackTrace();
}
String start = "07:15";
Date startBus=null;
try {
startBus = sdfDate.parse(start);
} catch (ParseException e) {
e.printStackTrace();
}
String user_time = getCurrentTimeStamp();
Date now = null;
try {
now = sdfDate.parse(user_time);
} catch (ParseException e) {
e.printStackTrace();
}
if (now.after(limitBus)||now.before(startBus)){
Toast.makeText(this, "Bus Operation Hours : 7:15AM - 11.00PM", Toast.LENGTH_LONG).show();
search.setEnabled(false);
}
else
{
search.setEnabled(true);
}
//get current time method
public static String getCurrentTimeStamp() {
SimpleDateFormat sdfDate = new SimpleDateFormat("HH:mm");//dd/MM/yyyy
Date now = new Date();
String strDate = sdfDate.format(now);
return strDate;
}
This code will check User Inputted time with current system time and will return time difference in long value.
public long getTimeDifferenceInMillis (String dateTime) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long currentTime = new Date().getTime();
long endTime = 0;
try {
//Parsing the user Inputed time ("yyyy-MM-dd HH:mm:ss")
endTime = dateFormat.parse(dateTime).getTime();
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
if (endTime > currentTime)
return endTime - currentTime;
else
return 0;
}
The user should pass the time in "yyyy-MM-dd HH:mm:ss" format.

java get the first date and last date of given month and given year [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.
I am trying to get the first date and the last date of the given month and year. I used the following code to get the last date in the format yyyyMMdd. But couldnot get this format. Also then I want the start date in the same format. I am still working on this. Can anyone help me in fixing the below code.
public static java.util.Date calculateMonthEndDate(int month, int year) {
int[] daysInAMonth = { 29, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int day = daysInAMonth[month];
boolean isLeapYear = new GregorianCalendar().isLeapYear(year);
if (isLeapYear && month == 2) {
day++;
}
GregorianCalendar gc = new GregorianCalendar(year, month - 1, day);
java.util.Date monthEndDate = new java.util.Date(gc.getTime().getTime());
return monthEndDate;
}
public static void main(String[] args) {
int month = 3;
int year = 2076;
final java.util.Date calculatedDate = calculateMonthEndDate(month, year);
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
format.format(calculatedDate);
System.out.println("Calculated month end date : " + calculatedDate);
}
java.time.YearMonth methods atDay & atEndOfMonth
The java.time framework built into Java 8+ (Tutorial) has commands for this.
The aptly-named YearMonth class represents a month of a year, without any specific day or time. From there we can ask for the first and days of the month.
YearMonth yearMonth = YearMonth.of( 2015, 1 ); // 2015-01. January of 2015.
LocalDate firstOfMonth = yearMonth.atDay( 1 ); // 2015-01-01
LocalDate lastOfMonth = yearMonth.atEndOfMonth(); // 2015-01-31
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.
Simply you can use Calendar class. you should assign month variable which month you want
Calendar gc = new GregorianCalendar();
gc.set(Calendar.MONTH, month);
gc.set(Calendar.DAY_OF_MONTH, 1);
Date monthStart = gc.getTime();
gc.add(Calendar.MONTH, 1);
gc.add(Calendar.DAY_OF_MONTH, -1);
Date monthEnd = gc.getTime();
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
System.out.println("Calculated month start date : " + format.format(monthStart));
System.out.println("Calculated month end date : " + format.format(monthEnd));
First day:
Calendar.getInstance().getActualMinimum(Calendar.DAY_OF_MONTH);
Last day of month:
Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH);
To get the Start Date
GregorianCalendar gc = new GregorianCalendar(year, month-1, 1);
java.util.Date monthEndDate = new java.util.Date(gc.getTime().getTime());
System.out.println(monthEndDate);
(Note : in the Start date the day =1)
for the formatted
SimpleDateFormat format = new SimpleDateFormat(/////////add your format here);
System.out.println("Calculated month end date : " + format.format(calculatedDate));
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
format.format(calculatedDate);
System.out.println("Calculated month end date : " + calculatedDate);
Change it to
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
String formattedDate = format.format(calculatedDate);
System.out.println("Calculated month end date : " + formattedDate);
For more detail
http://docs.oracle.com/javase/1.5.0/docs/api/java/text/DateFormat.html#format(java.util.Date)
Another Approach
package com.shashi.mpoole;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class DateMagic {
public static String PATTERN = "yyyyMMdd";
static class Measure {
private int month;
private int year;
private Calendar calendar;
public Measure build() {
calendar = Calendar.getInstance();
calendar.set(year, month, 1);
return this;
}
public Measure(int year, int month) {
this.year(year);
this.month(month);
}
public String min() {
return format(calendar.getActualMinimum(Calendar.DATE));
}
public String max() {
return format(calendar.getActualMaximum(Calendar.DATE));
}
private Date date(GregorianCalendar c) {
return new java.util.Date(c.getTime().getTime());
}
private GregorianCalendar gc(int day) {
return new GregorianCalendar(year, month, day);
}
private String format(int day) {
SimpleDateFormat format = new SimpleDateFormat(PATTERN);
return format.format(date(gc(day)));
}
public void month(int month) {
this.month = month - 1;
}
public void year(int year) {
this.year = year;
}
}
public static void main(String[] args) {
Measure measure = new Measure(2020, 6).build();
System.out.println(measure.min());
System.out.println(measure.max());
}
}
Try below code for last day of month : -
Calendar c = Calendar.getInstance();
c.set(2012,3,1); //------>
c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(sdf.format(c.getTime()));
http://www.coderanch.com/t/385759/java/java/date-date-month
Although, not exactly the answer for the OP question, below methods will given current month first & last dates as Java 8+ LocalDate instances.
public static LocalDate getCurrentMonthFirstDate() {
return LocalDate.ofEpochDay(System.currentTimeMillis() / (24 * 60 * 60 * 1000) ).withDayOfMonth(1);
}
public static LocalDate getCurrentMonthLastDate() {
return LocalDate.ofEpochDay(System.currentTimeMillis() / (24 * 60 * 60 * 1000) ).plusMonths(1).withDayOfMonth(1).minusDays(1);
}
Side note: Using LocalDate.ofEpochDay(...) instead of LocalDate.now() gives much improved performance. Also, using the millis-in-a-day expression instead of the end value, which is 86400000 is performing better. I initially thought the latter would perform better than the the expression :P
Why this answer: Even this is not a correct answer for OP question, I m still answering here as Google showed this question when I searched for 'java 8 get month start date' :)
GregorianCalendar gc = new GregorianCalendar(year, selectedMonth-1, 1);
java.util.Date monthStartDate = new java.util.Date(gc.getTime().getTime());
Calendar calendar = Calendar.getInstance();
calendar.setTime(monthStartDate);
calendar.add(calendar.MONTH, 1);
calendar.add(calendar.DAY_OF_MONTH, -1);
java.util.Date monthEndDate = new java.util.Date(calendar.getTime())
public static Date[] getMonthInterval(Date data) throws Exception {
Date[] dates = new Date[2];
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
start.setTime(data);
start.set(Calendar.DAY_OF_MONTH, start.getActualMinimum(Calendar.DAY_OF_MONTH));
start.set(Calendar.HOUR_OF_DAY, 0);
start.set(Calendar.MINUTE, 0);
start.set(Calendar.SECOND, 0);
end.setTime(data);
end.set(Calendar.DAY_OF_MONTH, end.getActualMaximum(Calendar.DAY_OF_MONTH));
end.set(Calendar.HOUR_OF_DAY, 23);
end.set(Calendar.MINUTE, 59);
end.set(Calendar.SECOND, 59);
//System.out.println("start "+ start.getTime());
//System.out.println("end "+ end.getTime());
dates[0] = start.getTime();
dates[1] = end.getTime();
return dates;
}

How can I find the number of years between two dates?

I am trying to determine an age in years from a certain date. Does anyone know a clean way to do this in Android? I have the Java api available obviously, but the straight-up java api is pretty weak, and I was hoping that Android has something to help me out.
EDIT: The multiple recommendations to use Joda time in Android worries me a bit due to Android Java - Joda Date is slow and related concerns. Also, pulling in a library not shipped with the platform for something this size is probably overkill.
import java.util.Calendar;
import java.util.Locale;
import static java.util.Calendar.*;
import java.util.Date;
public static int getDiffYears(Date first, Date last) {
Calendar a = getCalendar(first);
Calendar b = getCalendar(last);
int diff = b.get(YEAR) - a.get(YEAR);
if (a.get(MONTH) > b.get(MONTH) ||
(a.get(MONTH) == b.get(MONTH) && a.get(DATE) > b.get(DATE))) {
diff--;
}
return diff;
}
public static Calendar getCalendar(Date date) {
Calendar cal = Calendar.getInstance(Locale.US);
cal.setTime(date);
return cal;
}
Note: as Ole V.V. noticed, this won't work with dates before Christ due how Calendar works.
tl;dr
ChronoUnit.YEARS.between(
LocalDate.of( 2010 , 1 , 1 ) ,
LocalDate.now( ZoneId.of( "America/Montreal" ) )
)
Test for zero years elapsed, and one year elapsed.
ChronoUnit.YEARS.between(
LocalDate.of( 2010 , 1 , 1 ) ,
LocalDate.of( 2010 , 6 , 1 )
)
0
ChronoUnit.YEARS.between(
LocalDate.of( 2010 , 1 , 1 ) ,
LocalDate.of( 2011 , 1 , 1 )
)
1
See this code run at Ideone.com.
java.time
The old date-time classes really are bad, so bad that both Sun & Oracle agreed to supplant them with the java.time classes. If you do any significant work at all with date-time values, adding a library to your project is worthwhile. The Joda-Time library was highly successful and recommended, but is now in maintenance mode. The team advises migration to the java.time classes.
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…).
LocalDate start = LocalDate.of( 2010 , 1 , 1 ) ;
LocalDate stop = LocalDate.now( ZoneId.of( "America/Montreal" ) );
long years = java.time.temporal.ChronoUnit.YEARS.between( start , stop );
Dump to console.
System.out.println( "start: " + start + " | stop: " + stop + " | years: " + years ) ;
start: 2010-01-01 | stop: 2016-09-06 | years: 6
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….
I would recommend using the great Joda-Time library for everything date related in Java.
For your needs you can use the Years.yearsBetween() method.
I apparently can't comment yet, but I think you can just use the DAY_OF_YEAR to workout if you should adjust the years down one (copied and modified from current best answer)
public static int getDiffYears(Date first, Date last) {
Calendar a = getCalendar(first);
Calendar b = getCalendar(last);
int diff = b.get(Calendar.YEAR) - a.get(Calendar.YEAR);
if (a.get(Calendar.DAY_OF_YEAR) > b.get(Calendar.DAY_OF_YEAR)) {
diff--;
}
return diff;
}
public static Calendar getCalendar(Date date) {
Calendar cal = Calendar.getInstance(Locale.US);
cal.setTime(date);
return cal;
}
Similarly you could probably just diff the ms representations of the time and divide by the number of ms in a year. Just keep everything in longs and that should be good enough most of the time (leap years, ouch) but it depends on your application for the number of years and how performant that function has to be weather it would be worth that kind of hack.
I know you have asked for a clean solution, but here are two dirty once:
static void diffYears1()
{
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Calendar calendar1 = Calendar.getInstance(); // now
String toDate = dateFormat.format(calendar1.getTime());
Calendar calendar2 = Calendar.getInstance();
calendar2.add(Calendar.DAY_OF_YEAR, -7000); // some date in the past
String fromDate = dateFormat.format(calendar2.getTime());
// just simply add one year at a time to the earlier date until it becomes later then the other one
int years = 0;
while(true)
{
calendar2.add(Calendar.YEAR, 1);
if(calendar2.getTimeInMillis() < calendar1.getTimeInMillis())
years++;
else
break;
}
System.out.println(years + " years between " + fromDate + " and " + toDate);
}
static void diffYears2()
{
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Calendar calendar1 = Calendar.getInstance(); // now
String toDate = dateFormat.format(calendar1.getTime());
Calendar calendar2 = Calendar.getInstance();
calendar2.add(Calendar.DAY_OF_YEAR, -7000); // some date in the past
String fromDate = dateFormat.format(calendar2.getTime());
// first get the years difference from the dates themselves
int years = calendar1.get(Calendar.YEAR) - calendar2.get(Calendar.YEAR);
// now make the earlier date the same year as the later
calendar2.set(Calendar.YEAR, calendar1.get(Calendar.YEAR));
// and see if new date become later, if so then one year was not whole, so subtract 1
if(calendar2.getTimeInMillis() > calendar1.getTimeInMillis())
years--;
System.out.println(years + " years between " + fromDate + " and " + toDate);
}
Here's what I think is a better method:
public int getYearsBetweenDates(Date first, Date second) {
Calendar firstCal = GregorianCalendar.getInstance();
Calendar secondCal = GregorianCalendar.getInstance();
firstCal.setTime(first);
secondCal.setTime(second);
secondCal.add(Calendar.DAY_OF_YEAR, 1 - firstCal.get(Calendar.DAY_OF_YEAR));
return secondCal.get(Calendar.YEAR) - firstCal.get(Calendar.YEAR);
}
EDIT
Apart from a bug which I fixed, this method does not work well with leap years. Here's a complete test suite. I guess you're better off using the accepted answer.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
class YearsBetweenDates {
public static int getYearsBetweenDates(Date first, Date second) {
Calendar firstCal = GregorianCalendar.getInstance();
Calendar secondCal = GregorianCalendar.getInstance();
firstCal.setTime(first);
secondCal.setTime(second);
secondCal.add(Calendar.DAY_OF_YEAR, 1 - firstCal.get(Calendar.DAY_OF_YEAR));
return secondCal.get(Calendar.YEAR) - firstCal.get(Calendar.YEAR);
}
private static class TestCase {
public Calendar date1;
public Calendar date2;
public int expectedYearDiff;
public String comment;
public TestCase(Calendar date1, Calendar date2, int expectedYearDiff, String comment) {
this.date1 = date1;
this.date2 = date2;
this.expectedYearDiff = expectedYearDiff;
this.comment = comment;
}
}
private static TestCase[] tests = {
new TestCase(
new GregorianCalendar(2014, Calendar.JULY, 15),
new GregorianCalendar(2015, Calendar.JULY, 15),
1,
"exactly one year"),
new TestCase(
new GregorianCalendar(2014, Calendar.JULY, 15),
new GregorianCalendar(2017, Calendar.JULY, 14),
2,
"one day less than 3 years"),
new TestCase(
new GregorianCalendar(2015, Calendar.NOVEMBER, 3),
new GregorianCalendar(2017, Calendar.MAY, 3),
1,
"a year and a half"),
new TestCase(
new GregorianCalendar(2016, Calendar.JULY, 15),
new GregorianCalendar(2017, Calendar.JULY, 15),
1,
"leap years do not compare correctly"),
};
public static void main(String[] args) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
for (TestCase t : tests) {
int diff = getYearsBetweenDates(t.date1.getTime(), t.date2.getTime());
String result = diff == t.expectedYearDiff ? "PASS" : "FAIL";
System.out.println(t.comment + ": " +
df.format(t.date1.getTime()) + " -> " +
df.format(t.date2.getTime()) + " = " +
diff + ": " + result);
}
}
}
a handy one if you don't want to border Calendar, Locale, or external library:
private static SimpleDateFormat YYYYMMDD = new SimpleDateFormat("yyyyMMdd");
public static Integer toDate8d(Date date) {
String s;
synchronized (YYYYMMDD) { s = YYYYMMDD.format(date); } // SimpleDateFormat thread safety
return Integer.valueOf(s);
}
public static Integer yearDiff(Date pEarlier, Date pLater) {
return (toDate8d(pLater) - toDate8d(pEarlier)) / 10000;
}
If you don't want to calculate it using java's Calendar you can use Androids Time class It is supposed to be faster but I didn't notice much difference when i switched.
I could not find any pre-defined functions to determine time between 2 dates for an age in Android. There are some nice helper functions to get formatted time between dates in the DateUtils but that's probably not what you want.
// int year =2000; int month =9 ; int day=30;
public int getAge (int year, int month, int day) {
GregorianCalendar cal = new GregorianCalendar();
int y, m, d, noofyears;
y = cal.get(Calendar.YEAR);// current year ,
m = cal.get(Calendar.MONTH);// current month
d = cal.get(Calendar.DAY_OF_MONTH);//current day
cal.set(year, month, day);// here ur date
noofyears = y - cal.get(Calendar.YEAR);
if ((m < cal.get(Calendar.MONTH))
|| ((m == cal.get(Calendar.MONTH)) && (d < cal
.get(Calendar.DAY_OF_MONTH)))) {
--noofyears;
}
if(noofyears < 0)
throw new IllegalArgumentException("age < 0");
System.out.println(noofyears);
return noofyears;
This will work and if you want the number of years replace 12 to 1
String date1 = "07-01-2015";
String date2 = "07-11-2015";
int i = Integer.parseInt(date1.substring(6));
int j = Integer.parseInt(date2.substring(6));
int p = Integer.parseInt(date1.substring(3,5));
int q = Integer.parseInt(date2.substring(3,5));
int z;
if(q>=p){
z=q-p + (j-i)*12;
}else{
z=p-q + (j-i)*12;
}
System.out.println("The Total Months difference between two dates is --> "+z+" Months");
Thanks #Ole V.v for reviewing it: i have found some inbuilt library classes which does the same
int noOfMonths = 0;
org.joda.time.format.DateTimeFormatter formatter = DateTimeFormat
.forPattern("yyyy-MM-dd");
DateTime dt = formatter.parseDateTime(startDate);
DateTime endDate11 = new DateTime();
Months m = Months.monthsBetween(dt, endDate11);
noOfMonths = m.getMonths();
System.out.println(noOfMonths);
Try this:
int getYear(Date date1,Date date2){
SimpleDateFormat simpleDateformat=new SimpleDateFormat("yyyy");
Integer.parseInt(simpleDateformat.format(date1));
return Integer.parseInt(simpleDateformat.format(date2))- Integer.parseInt(simpleDateformat.format(date1));
}

How do I add one month to current date in Java?

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

Categories

Resources