How do I add one month to current date in Java? - 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

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

Android how to get tomorrow's date

In my android application. I need to display tomorrow's date, for example today is 5th March so I need to display as 6 March. I know the code for getting today's date, month and year.
date calculating
GregorianCalendar gc = new GregorianCalendar();
yearat = gc.get(Calendar.YEAR);
yearstr = Integer.toString(yearat);
monthat = gc.get(Calendar.MONTH) + 1;
monthstr = Integer.toString(monthat);
dayat = gc.get(Calendar.DAY_OF_MONTH);
daystr = Integer.toString(dayat);
If I have the code
dayat = gc.get(Calendar.DAY_OF_MONTH) + 1;
will it display tomorrow's date. or just add one to today's date? For example, if today is January 31. With the above code, will it display like 1 or 32? If it displays 32, what change I need to make?
Get today's date as a Calendar.
Add 1 day to it.
Format for display purposes.
For example,
GregorianCalendar gc = new GregorianCalendar();
gc.add(Calendar.DATE, 1);
// now do something with the calendar
Use the following code to display tomorrow date
Calendar calendar = Calendar.getInstance();
Date today = calendar.getTime();
calendar.add(Calendar.DAY_OF_YEAR, 1);
Date tomorrow = calendar.getTime();
Use SimpleDateFormat to format the Date as a String:
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
String todayAsString = dateFormat.format(today);
String tomorrowAsString = dateFormat.format(tomorrow);
System.out.println(todayAsString);
System.out.println(tomorrowAsString);
Prints:
05-Mar-2014
06-Mar-2014
Calendar calendar = Calendar.getInstance();
Date today = calendar.getTime();
calendar.add(Calendar.DAY_OF_YEAR, 1);
Date tomorrow = calendar.getTime();
you have to add just 1 in your Calendar Day.
GregorianCalendar gc = new GregorianCalendar();
gc.add(Calendar.DATE, 1);
java.util.Date and java.util.Calendar are terrible to work with. I suggest you use JodaTime which has a much cleaner / nicer API. JodaTime is pretty standard these days.
http://www.joda.org/joda-time/#Why_Joda-Time
Note that JDK 8 will introduce a new date/time API heavily influenced by JodaTime.
http://java.dzone.com/articles/introducing-new-date-and-time
https://jcp.org/en/jsr/detail?id=310
Other options:
Calendar tomorrow = Calendar.getInstance();
tomorrow.roll(Calendar.DATE, true);
or
tomorrow.roll(Calendar.DATE, 1);
roll can also be used to go back in time by passing a negative number, so for example:
Calendar yesterday = Calendar.getInstance();
yesterday.roll(Calendar.DATE, -1);
the first answers pretty much covers the possibilities.
but here one another solution which you can use from org.apache.commons.lang.time:
Date lTomorrow = DateUtils.addDays(new Date(), 1);
The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. Instead use either Joda-Time library or the new java.time package in bundled with Java 8.
Some example code using the Joda-Time 2.3 library.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime now = new DateTime( timeZone );
DateTime tomorrow = now.plusDays( 1 );
String output = DateTimeFormat.forPattern( "FF" ).withLocale(Locale.FRANCE).print( tomorrow );
Get todays date by using calendar and then add 1 day to it.
This is working to me well!!
Date currentDate = new Date();// get the current date
currentDate.setDate(currentDate.getDate() + 1);//add one day to the current date
dateView.setText(currentDate.toString().substring(0, 10));// put the string in specific format in my textView
good luck!!
much easier now
String today = LocalDateTime.now().format(DateTimeFormatter.ofPattern("MM-dd"));
String tomorrow = LocalDate.now().plusDays(1).format(DateTimeFormatter.ofPattern("MM-dd"));
Try like this..
dayat = gc.add(Calendar.DATE, 1);
tl;dr
java.time.LocalDate.now()
.plusDays( 1 )
java.time
All the other Answers are outmoded, using the troublesome old Date & Calendar classes or the Joda-Time project which is now in maintenance mode. The modern approach uses the java.time classes.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
From that LocalDate you can do math to get the following day.
LocalDate tomorrow = today.plusDays( 1 ) ;
Strings
To generate a String representing the LocalDate object’s value, call toString for text formatted per the ISO 8601 standard: YYYY-MM-DD.
To generate strings in other formats, search Stack Overflow for DateTimeFormatter.
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….
Best way for setting next day is
public void NextDate()
{
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
// set current date into textview
e_date.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(mDay+1).append("-").append(mMonth + 1).append("-")
.append(mYear).append(" "));
}
Just call this method and send date from which you want next date
public String nextDate(Date dateClicked) {
//
String next_day;
calander_view.setCurrentDayTextColor(context.getResources().getColor(R.color.white_color));
//calander_view.setCurrentDayBackgroundColor(context.getResources().getColor(R.color.gray_color));
SimpleDateFormat dateFormatForDisplaying = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
String date_format = dateFormatForDisplaying.format(dateClicked);
SimpleDateFormat simpleDateformat = new SimpleDateFormat("E"); // the day of the week abbreviated
final Calendar calendar = Calendar.getInstance();
try {
Date date = dateFormatForDisplaying.parse(date_format);
calendar.setTime(date);
calendar.add(Calendar.DATE, 1);
String nex = dateFormatForDisplaying.format(calendar.getTime());
Date d1 = dateFormatForDisplaying.parse(nex);
String day_1 = simpleDateformat.format(d1);
next_day = nex + ", " + day_1;
} catch (ParseException e) {
e.printStackTrace();
}
return next_day;
}
String lastDate="5/28/2018";
Calendar calendar = Calendar.getInstance();
String[] sDate=lastDate.split("/");
calendar.set(Integer.parseInt(sDate[2]),Integer.parseInt(sDate[0]),Integer.parseInt(sDate[1]));
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
// String todayAsString = dateFormat.format(today);
for (int i=1;i<29;i++)
{
calendar.add(Calendar.DAY_OF_YEAR,1);
// td[i].setText(dateFormat.format(calendar.getTime()));
System.out.println(dateFormat.format(calendar.getTime()));
}

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;
}

Android: how to get the current day of the week (Monday, etc...) in the user's language?

I want to know what the current day of the week is (Monday, Tuesday...) in the user's local language. For example, "Lundi" "Mardi" etc... if the user is French.
I have read this post, it but it only returns an int, not a string with the day in the user's language: What is the easiest way to get the current day of the week in Android?
More generally, how do you get all the days of the week and all the months of the year written in the user's language ?
I think that this is possible, as for example the Google agenda gives the days and months written in the user's local language.
Use SimpleDateFormat to format dates and times into a human-readable string, with respect to the users locale.
Small example to get the current day of the week (e.g. "Monday"):
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date d = new Date();
String dayOfTheWeek = sdf.format(d);
Try this:
int dayOfWeek = date.get(Calendar.DAY_OF_WEEK);
String weekday = new DateFormatSymbols().getShortWeekdays()[dayOfWeek];
I know already answered but who looking for 'Fri' like this
for Fri -
SimpleDateFormat sdf = new SimpleDateFormat("EEE");
Date d = new Date();
String dayOfTheWeek = sdf.format(d);
and who wants full date string they can use 4E for Friday
For Friday-
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date d = new Date();
String dayOfTheWeek = sdf.format(d);
Enjoy...
To make things shorter You can use this:
android.text.format.DateFormat.format("EEEE", date);
which will return day of the week as a String.
Hers's what I used to get the day names (0-6 means monday - sunday):
public static String getFullDayName(int day) {
Calendar c = Calendar.getInstance();
// date doesn't matter - it has to be a Monday
// I new that first August 2011 is one ;-)
c.set(2011, 7, 1, 0, 0, 0);
c.add(Calendar.DAY_OF_MONTH, day);
return String.format("%tA", c);
}
public static String getShortDayName(int day) {
Calendar c = Calendar.getInstance();
c.set(2011, 7, 1, 0, 0, 0);
c.add(Calendar.DAY_OF_MONTH, day);
return String.format("%ta", c);
}
Try this...
//global declaration
private TextView timeUpdate;
Calendar calendar;
.......
timeUpdate = (TextView) findViewById(R.id.timeUpdate); //initialize in onCreate()
.......
//in onStart()
calendar = Calendar.getInstance();
//date format is: "Date-Month-Year Hour:Minutes am/pm"
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy HH:mm a"); //Date and time
String currentDate = sdf.format(calendar.getTime());
//Day of Name in full form like,"Saturday", or if you need the first three characters you have to put "EEE" in the date format and your result will be "Sat".
SimpleDateFormat sdf_ = new SimpleDateFormat("EEEE");
Date date = new Date();
String dayName = sdf_.format(date);
timeUpdate.setText("" + dayName + " " + currentDate + "");
The result is...
tl;dr
String output =
LocalDate.now( ZoneId.of( "America/Montreal" ) )
.getDayOfWeek()
.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ;
java.time
The java.time classes built into Java 8 and later and back-ported to Java 6 & 7 and to Android include the handy DayOfWeek enum.
The days are numbered according to the standard ISO 8601 definition, 1-7 for Monday-Sunday.
DayOfWeek dow = DayOfWeek.of( 1 );
This enum includes the getDisplayName method to generate a String of the localized translated name of the day.
The Locale object specifies a human language to be used in translation, and specifies cultural norms to decide issues such as capitalization and punctuation.
String output = DayOfWeek.MONDAY.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ;
To get today’s date, use the LocalDate class. Note that a time zone is crucial as for any given moment the date varies around the globe.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
DayOfWeek dow = today.getDayOfWeek();
String output = dow.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ;
Keep in mind that the locale has nothing to do with the time zone.two separate distinct orthogonal issues. You might want a French presentation of a date-time zoned in India (Asia/Kolkata).
Joda-Time
UPDATE: The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
The Joda-Time library provides Locale-driven localization of date-time values.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( zone );
Locale locale = Locale.CANADA_FRENCH;
DateTimeFormatter formatterUnJourQuébécois = DateTimeFormat.forPattern( "EEEE" ).withLocale( locale );
String output = formatterUnJourQuébécois.print( now );
System.out.println("output: " + output );
output: samedi
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 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
Sorry for late reply.But this would work properly.
daytext=(textview)findviewById(R.id.day);
Calender c=Calender.getInstance();
SimpleDateFormat sd=new SimpleDateFormat("EEEE");
String dayofweek=sd.format(c.getTime());
daytext.setText(dayofweek);
I just use this solution in Kotlin:
var date : String = DateFormat.format("EEEE dd-MMM-yyyy HH:mm a" , Date()) as String
If you are using ThreetenABP date library bt Jake Warthon you can do:
dayOfWeek.getDisplayName(TextStyle.FULL, Locale.getDefault()
on your dayOfWeek instance. More at:
https://github.com/JakeWharton/ThreeTenABP https://www.threeten.org/threetenbp/apidocs/org/threeten/bp/format/TextStyle.html
//selected date from calender
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy"); //Date and time
String currentDate = sdf.format(myCalendar.getTime());
//selcted_day name
SimpleDateFormat sdf_ = new SimpleDateFormat("EEEE");
String dayofweek=sdf_.format(myCalendar.getTime());
current_date.setText(currentDate);
lbl_current_date.setText(dayofweek);
Log.e("dayname", dayofweek);

Compare two dates in 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");
}

Categories

Resources