Basically I want to see if someones birthday is within 3 months of todays date. I am going to use Days to do this and just say "90" days.
My thoughts are as follows:
I will set a new datetime as todays date and then grab the DOB of the person in question.
I will then want to take the day and month from the DOB and the year from Todays date.
Then these days, months and years will be merged into one new date.
For example:
DOB 04/05/1987
Today 10/05/2013
NewBirth 04/05/2013
How can I achieve the part where I grab the days/months from one date, years from another, and put these into one date?
(Only key factors, im aware this rule wouldn't run)
import org.joda.time.ReadableInstant;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.Months;
import org.joda.time.Years;
rule"Blah"
salience 1
when
Proposer($dob : dateOfBirth)
then
DateTime NewBirth = new DateTime()
DateTime today = new DateTime();
#grab DOB day and month
#grab Todays year
#turn "NewBirth" into a combination of the above 2 lines
int $birthday = (Days.daysBetween((ReadableInstant)today,(ReadableInstant)NewBirth).getDays());
If ($birthday <= 90){
logger.info("HURRRAAAYYYYYY");
}
end
I would do it with the standard JDK Calendar
boolean isWithin3Month(int y, int m, int d) {
Calendar now = Calendar.getInstance();
Calendar birthday = new GregorianCalendar(y, m, d);
int currentMonth = now.get(Calendar.MONTH);
int birthDayMonth = birthday.get(Calendar.MONTH);
int monthDiff;
if (birthDayMonth < currentMonth) { // eg birth = Jan (0) and curr = Dec (11)
monthDiff = 12 - currentMonth + birthDayMonth;
} else {
monthDiff = birthDayMonth - currentMonth;
}
if (monthDiff < 0 || monthDiff > 3) {
return false;
} else if (monthDiff == 0) {
return birthday.get(Calendar.DATE) >= now.get(Calendar.DATE);
}
return true;
}
java.time
The Joda-Time project is now in maintenance mode, with the team advising migration to 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.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
You apparently want to know if the birthday anniversary lands between today and 90 days from today. So determine that 90 day limit.
LocalDate ninetyDaysFromToday = today.plusDays( 90 );
Get the birthdate.
LocalDate birthdate = LocalDate.of( 1987 , Month.APRIL , 5 ) ;
MonthDay
The MonthDay class represents, well, a month and a day-of-month, without any year. You can adjust into a year to get a date. Perfect for adjusting that birthday into this year.
If the birthday of this year is already past, then we need to consider next year’s birthday, as the 90 day limit may wrap over into the new year.
MonthDay mdBirthday = MonthDay.from( birthdate );
MonthDay mdToday = MonthDay.from( today );
int y = mdBirthday.isBefore( mdToday ) ? ( today.getYear()+1 ) : today.getYear() ;
LocalDate nextBirthday = mdBirthday.atYear( y );
Boolean nextBirthdayIsWithinNextNinetyDays = nextBirthday.isBefore( ninetyDaysFromToday );
Or another way to do the same.
LocalDate nextBirthday = MonthDay.from( birthdate ).atYear( today.getYear() ) ; // Possibly the next birthday, not yet sure.
if( nextBirthday.isBefore( today ) ) {
// This year’s birthday is past, so increment the year to get next birthday.
nextBirthday = nextBirthday.plusYears( 1 );
}
Boolean nextBirthdayIsWithinNextNinetyDays = nextBirthday.isBefore( ninetyDaysFromToday );
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, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Try
DateTime newBirth = new DateTime(today.year(), $dob.monthOfYear(), $dob.dayOfMonth(), 00, 00);
instead of the parameterless constructer at the beginning of your then statement.
Ended up managing to do it with Jodatime,
rule"Less than 3months before Birthday Discount"
when
Proposer($dob : dateOfBirth)
then
DateTime today = new DateTime();
DateTime newBirth = new DateTime(today.year().get()+"-"+$dob.monthOfYear().get()+"-"+$dob.dayOfMonth().get());
int $birthday = (Days.daysBetween((ReadableInstant)today,(ReadableInstant)newBirth).getDays());
if($birthday <=90 && $birthday>0){
logger.info("discount applied");
}
end
Related
This question already has answers here:
How do I check if a date is within a certain range?
(17 answers)
Closed 5 years ago.
How do I compare dates in between in Java?
Example:
date1 is 22-02-2010
date2 is 07-04-2010 today
date3 is 25-12-2010
date3 is always greater than date1 and date2 is always today. How do I verify if today's date is in between date1 and date 3?
Date has before and after methods and can be compared to each other as follows:
if(todayDate.after(historyDate) && todayDate.before(futureDate)) {
// In between
}
For an inclusive comparison:
if(!historyDate.after(todayDate) && !futureDate.before(todayDate)) {
/* historyDate <= todayDate <= futureDate */
}
You could also give Joda-Time a go, but note that:
Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time (JSR-310).
Back-ports are available for Java 6 and 7 as well as Android.
Use compareTo:
date1.compareTo(date2);
Following are most common way of comparing dates (my preference is Approach 1):
Approach 1: Using Date.before(), Date.after() and Date.equals()
if (date1.after(date2)) {
System.out.println("Date1 is after Date2");
}
if (date1.before(date2)) {
System.out.println("Date1 is before Date2");
}
if (date1.equals(date2)) {
System.out.println("Date1 is equal Date2");
}
Approach 2: Date.compareTo()
if (date1.compareTo(date2) > 0) {
System.out.println("Date1 is after Date2");
} else if (date1.compareTo(date2) < 0) {
System.out.println("Date1 is before Date2");
} else {
System.out.println("Date1 is equal to Date2");
}
Approach 3: Calender.before(), Calender.after() and Calender.equals()
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
if (cal1.after(cal2)) {
System.out.println("Date1 is after Date2");
}
if (cal1.before(cal2)) {
System.out.println("Date1 is before Date2");
}
if (cal1.equals(cal2)) {
System.out.println("Date1 is equal Date2");
}
tl;dr
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) ) ;
Boolean isBetween =
( ! today.isBefore( localDate1 ) ) // “not-before” is short for “is-equal-to or later-than”.
&&
today.isBefore( localDate3 ) ;
Or, better, if you add the ThreeTen-Extra library to your project.
LocalDateRange.of(
LocalDate.of( … ) ,
LocalDate.of( … )
).contains(
LocalDate.now()
)
Half-open approach, where beginning is inclusive while ending is exclusive.
Bad Choice of Format
By the way, that is a bad choice of format for a text representation of a date or date-time value. Whenever possible, stick with the standard ISO 8601 formats. ISO 8601 formats are unambiguous, understandable across human cultures, and are easy to parse by machine.
For a date-only value, the standard format is YYYY-MM-DD. Note how this format has the benefit of being chronological when sorted alphabetically.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
DateTimeFormatter
As your input strings are non-standard format, we must define a formatting pattern to match.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" );
Use that to parse the input strings.
LocalDate start = LocalDate.parse( "22-02-2010" , f );
LocalDate stop = LocalDate.parse( "25-12-2010" , f );
In date-time work, usually best to define a span of time by the Half-Open approach where the beginning is inclusive while the ending is exclusive. So we want to know if today is the same or later than the start and also before the stop. A briefer way of saying “is the same or later than the start” is “not before the start”.
Boolean intervalContainsToday = ( ! today.isBefore( start ) ) && today.isBefore( stop ) ;
See the Answer by gstackoverflow showing the list of comparison methods you can call.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 brought some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
UPDATE: This “Joda-Time” section below is left intact as history. The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
Joda-Time
Other answers are correct with regard to the bundled java.util.Date and java.util.Calendar classes. But those classes are notoriously troublesome. So here's some example code using the Joda-Time 2.3 library.
If you truly want a date without any time portion and no time zone, then use the LocalDate class in Joda-Time. That class provides methods of comparison including compareTo (used with Java Comparators), isBefore, isAfter, and isEqual.
Inputs…
String string1 = "22-02-2010";
String string2 = "07-04-2010";
String string3 = "25-12-2010";
Define a formatter describing the input strings…
DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd-MM-yyyy" );
Use formatter to parse the strings into LocalDate objects…
LocalDate localDate1 = formatter.parseLocalDate( string1 );
LocalDate localDate2 = formatter.parseLocalDate( string2 );
LocalDate localDate3 = formatter.parseLocalDate( string3 );
boolean is1After2 = localDate1.isAfter( localDate2 );
boolean is2Before3 = localDate2.isBefore( localDate3 );
Dump to console…
System.out.println( "Dates: " + localDate1 + " " + localDate2 + " " + localDate3 );
System.out.println( "is1After2 " + is1After2 );
System.out.println( "is2Before3 " + is2Before3 );
When run…
Dates: 2010-02-22 2010-04-07 2010-12-25
is1After2 false
is2Before3 true
So see if the second is between the other two (exclusively, meaning not equal to either endpoint)…
boolean is2Between1And3 = ( ( localDate2.isAfter( localDate1 ) ) && ( localDate2.isBefore( localDate3 ) ) );
Working With Spans Of Time
If you are working with spans of time, I suggest exploring in Joda-Time the classes: Duration, Interval, and Period. Methods such as overlap and contains make comparisons easy.
For text representations, look at the ISO 8601 standard’s:
durationFormat: PnYnMnDTnHnMnSExample: P3Y6M4DT12H30M5S(Means “three years, six months, four days, twelve hours, thirty minutes, and five seconds”)
intervalFormat: start/endExample: 2007-03-01T13:00:00Z/2008-05-11T15:30:00Z
Joda-Time classes can work with strings in both those formats, both as input (parsing) and output (generating strings).
Joda-Time performs comparisons using the Half-Open approach where the beginning of the span is inclusive while the ending is exclusive. This approach is a wise one for handling spans of time. Search StackOverflow for more info.
Compare the two dates:
Date today = new Date();
Date myDate = new Date(today.getYear(),today.getMonth()-1,today.getDay());
System.out.println("My Date is"+myDate);
System.out.println("Today Date is"+today);
if (today.compareTo(myDate)<0)
System.out.println("Today Date is Lesser than my Date");
else if (today.compareTo(myDate)>0)
System.out.println("Today Date is Greater than my date");
else
System.out.println("Both Dates are equal");
Update for Java 8 and later
isAfter()
isBefore()
isEqual()
compareTo()
These methods exists in LocalDate, LocalTime, and LocalDateTime classes.
Those classes are built into Java 8 and later. Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
You can use Date.getTime() which:
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
represented by this Date object.
This means you can compare them just like numbers:
if (date1.getTime() <= date.getTime() && date.getTime() <= date2.getTime()) {
/*
* date is between date1 and date2 (both inclusive)
*/
}
/*
* when date1 = 2015-01-01 and date2 = 2015-01-10 then
* returns true for:
* 2015-01-01
* 2015-01-01 00:00:01
* 2015-01-02
* 2015-01-10
* returns false for:
* 2014-12-31 23:59:59
* 2015-01-10 00:00:01
*
* if one or both dates are exclusive then change <= to <
*/
Try this
public static boolean compareDates(String psDate1, String psDate2) throws ParseException{
SimpleDateFormat dateFormat = new SimpleDateFormat ("dd/MM/yyyy");
Date date1 = dateFormat.parse(psDate1);
Date date2 = dateFormat.parse(psDate2);
if(date2.after(date1)) {
return true;
} else {
return false;
}
}
Use getTime() to get the numeric value of the date, and then compare using the returned values.
This code determine today is in some duration.. based on KOREA locale
Calendar cstart = Calendar.getInstance(Locale.KOREA);
cstart.clear();
cstart.set(startyear, startmonth, startday);
Calendar cend = Calendar.getInstance(Locale.KOREA);
cend.clear();
cend.set(endyear, endmonth, endday);
Calendar c = Calendar.getInstance(Locale.KOREA);
if(c.after(cstart) && c.before(cend)) {
// today is in startyear/startmonth/startday ~ endyear/endmonth/endday
}
This method worked for me:
public static String daysBetween(String day1, String day2) {
String daysBetween = "";
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date1 = myFormat.parse(day1);
Date date2 = myFormat.parse(day2);
long diff = date2.getTime() - date1.getTime();
daysBetween = ""+(TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
} catch (ParseException e) {
e.printStackTrace();
}
return daysBetween;
}
I have 2 dates like this :
DateTime startingDate = new DateTime(STARTING_YEAR, STARTING_MONTH, STARTING_DAY, 0, 0);
DateTime endingDate = new DateTime(ENDING_YEAR, ENDING_MONTH, ENDING_DAY, 0, 0);
TOTAL_DAYS = Days.daysBetween(startingDate, endingDate).getDays();
It is easy to know the total days between, but I'm not familiar at all with the API and would like to know if there is an easier way to find the number of days in each months between 2 dates without loops and ifs.
Example :
DateTime startingDate = new DateTime(2000, 1, 1, 0, 0);
DateTime endingDate = new DateTime(2000, 2, 3, 0, 0);
Would give 31 for January and 2 for February.
Thanks!
I did it with a loop finally.
DateTime startingDate = new DateTime(STARTING_YEAR, STARTING_MONTH, STARTING_DAY, 0, 0);
DateTime endingDate = new DateTime(ENDING_YEAR, ENDING_MONTH, ENDING_DAY, 0, 0);
TOTAL_DAYS = Days.daysBetween(startingDate, endingDate).getDays();
DateTime currentDate = startingDate;
System.out.println(currentDate.dayOfMonth().getMaximumValue() - currentDate.dayOfMonth().get() + 1);
currentDate = currentDate.plus(Period.months(1));
while (currentDate.isBefore(endingDate)) {
System.out.println(currentDate.dayOfMonth().getMaximumValue());
currentDate = currentDate.plus(Period.months(1));
}
System.out.println(endingDate.dayOfMonth().get());
double days = (endingDate.getMillis()-startingDate.getMillis())/86400000.0;
that gives the number of days as a floating point number. truncate if you only want the number of full days.
This may help:
DateTime startingDate = new DateTime(2000, 1, 1, 0, 0);
DateTime endingDate = new DateTime(2000, 2, 3, 0, 0);
Duration duration = new Duration(startingDate, endingDate);
System.out.println(duration.getStandardDays());//get the difference in number of days
FYI, the Joda-Time project, now in maintenance mode, advises migration to java.time.
java.time
You will need to iterate if you want to address each intervening month individually. But this job is somewhat simplified by the YearMonth class. Furthermore, you can mask away the iteration by using Streams.
Half-Open
The java.time classes wisely use the Half-Open approach to defining a span of time. This means the beginning is inclusive while the ending is exclusive. So a range of months needs to end with the month following the ending target month.
TemporalAdjuster
The TemporalAdjuster interface provides for manipulation of date-time values. The TemporalAdjusters class (note the plural s) provides several handy implementations. Here we need:
TemporalAdjusters.firstDayOfNextMonth()
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate startDate = LocalDate.of( 2000 , 1 , 1 );
YearMonth ymStart = YearMonth.from( startDate );
LocalDate stopDate = LocalDate.of( 2000 , 2 , 3 );
LocalDate stopDateNextMonth = stopDate.with( TemporalAdjusters.firstDayOfNextMonth() );
YearMonth ymStop = YearMonth.from( stopDateNextMonth );
Loop each month in between.
You can ask for a localized name of the month, by the way, via the Month enum object.
YearMonth ym = ymStart;
do {
int daysInMonth = ym.lengthOfMonth ();
String monthName = ym.getMonth ().getDisplayName ( TextStyle.FULL , Locale.CANADA_FRENCH );
System.out.println ( ym + " : " + daysInMonth + " jours en " + monthName );
// Prepare for next loop.
ym = ym.plusMonths ( 1 );
} while ( ym.isBefore ( ymStop ) );
2000-01 : 31 jours en janvier
2000-02 : 29 jours en février
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, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
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()));
}
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);
I'm trying to list all days of the week for current week from Monday to Sunday. For example, today (day of this posting) is September 4th, 2011 and it's Sunday.
I'm starting calendar and setting first day of the week to Monday:
Calendar cal = Calendar.getInstance();
cal.setFirstDayOfWeek(Calendar.MONDAY);
When I check day of the month, I get correct result:
int check = cal.get(Calendar.DAY_OF_MONTH);
// check is equal to 4
But when I set weekday to Monday, it jumps to the next week instead of returning Monday of this week:
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
int mon = cal.get(Calendar.DAY_OF_MONTH);
// mon is equal to 5, when expected to be 29 (last Monday of August)
Even setting weekday to Sunday returns next Sunday and not today.
Can someone explain why it works that way and what's the best way to solve this problem?
In fact, when I check my own tests, it seems to work as expected, except when the date is not set again:
Display 4-29:
Calendar cal = Calendar.getInstance();
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.setMinimalDaysInFirstWeek(4);
cal.set(2011, 8, 4);
int test = cal.get(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
int mon = cal.get(Calendar.DAY_OF_MONTH);
bTest.setText("" + test + "-" + mon);
Display 5-5:
Calendar cal = Calendar.getInstance();
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.setMinimalDaysInFirstWeek(4);
cal.set(2011, 8, 5);
int test = cal.get(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
int mon = cal.get(Calendar.DAY_OF_MONTH);
bTest.setText("" + test + "-" + mon);
Display 14-12:
Calendar cal = Calendar.getInstance();
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.setMinimalDaysInFirstWeek(4);
cal.set(2011, 8, 14);
int test = cal.get(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
int mon = cal.get(Calendar.DAY_OF_MONTH);
bTest.setText("" + test + "-" + mon);
So, this doesn't work:
Calendar cal = Calendar.getInstance();
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.setMinimalDaysInFirstWeek(4);
//cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
int test = cal.get(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
int mon = cal.get(Calendar.DAY_OF_MONTH);
bTest.setText("" + test + "-" + mon); // Display 4-5
and this works:
Calendar cal = Calendar.getInstance();
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.setMinimalDaysInFirstWeek(4);
// Workaround
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
int test = cal.get(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
int mon = cal.get(Calendar.DAY_OF_MONTH);
bTest.setText("" + test + "-" + mon); // Display 4-29
and this works too:
Calendar cal = Calendar.getInstance();
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.setMinimalDaysInFirstWeek(4);
// Workaround
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
cal.get(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
int mon = cal.get(Calendar.DAY_OF_MONTH);
bTest.setText("" + mon); // Display 29
But this one doesn't:
Calendar cal = Calendar.getInstance();
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.setMinimalDaysInFirstWeek(4);
// Workaround
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
int mon = cal.get(Calendar.DAY_OF_MONTH);
bTest.setText("" + mon); // Display 5
tl;dr
Use LocalDate, never Calendar.
LocalDate.now( ZoneId.of( "Africa/Tunis" ) )
.with( TemporalAdjusters.previousOrSame( DayOfWeek.MONDAY ) )
.plusDays( i ) )
java.time
Avoid the troublesome old legacy class Calendar as it is now legacy, supplanted by the java.time classes (specifically ZonedDateTime).
For date-only values without time-of-day, use LocalDate rather than a date+time type like Calendar or ZonedDateTime. The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.
LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ; // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.
Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety.
LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;
DayOfWeek
For day-of-week, use the DayOfWeek enum class. It offers seven instances, one for each day of the week, Monday-Sunday.
DayOfWeek dow = ld.getDayOfWeek() ; // Get an enum representing the day-of-week of this date, such as `DayOfWeek.MONDAY`.
Adjusting date
We need find the previous Monday, or stick with today’s date if already a Monday. To move to such dates, use the TemporalAdjusters.previousOrSame implementation of TemporalAdjuster.
TemporalAdjuster ta = TemporalAdjusters.previousOrSame( DayOfWeek.MONDAY ) ;
LocalDate previousOrSameMonday = ld.with( ta ) ;
Collect your desired dates by incrementing with a call to LocalDate.plusDays(). Notice how java.time uses immutable objects. We get a fresh object based on the values of the original rather than mutating (altering) the original.
// Hard-coded `7` is the seven days in a week.
List< LocalDate > dates = new ArrayList<>( 7 ) ;
for( int i = 0 , i < 7 , i ++ ) {
LocalDate localDate = previousOrSameMonday.plusDays( i ) ;
dates.add( localDate ) ;
}
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<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.
UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. This section left for history.
Joda-Time
what's the best way to solve this problem?
The best way is to avoid using the notoriously troublesome java.util.Date & .Calendar classes, and instead use the Joda-Time library. Joda-Time works in Android.
Joda-Time offers the LocalDate class for date-only values without any time or time zone.
Example Code
Here is some example code using Joda-Time 2.3.
LocalDate localDate = new LocalDate( 2011, DateTimeConstants.SEPTEMBER, 4 );
LocalDate firstDateOfWeek = localDate.withDayOfWeek( DateTimeConstants.MONDAY );
for ( int i = 0; i < 7; i++ ) {
LocalDate someDateOfWeek = firstDateOfWeek.plusDays( i );
System.out.println( "someDateOfWeek: " + someDateOfWeek + " le jour de la semaine: " + someDateOfWeek.dayOfWeek().getAsText( Locale.CANADA_FRENCH ) );
}
When run…
someDateOfWeek: 2011-08-29 le jour de la semaine: lundi
someDateOfWeek: 2011-08-30 le jour de la semaine: mardi
someDateOfWeek: 2011-08-31 le jour de la semaine: mercredi
someDateOfWeek: 2011-09-01 le jour de la semaine: jeudi
someDateOfWeek: 2011-09-02 le jour de la semaine: vendredi
someDateOfWeek: 2011-09-03 le jour de la semaine: samedi
someDateOfWeek: 2011-09-04 le jour de la semaine: dimanche
Week Number
Bonus tip: If you want the week number as defined by the ISO 8601 standard, call the weekOfWeekYear method. Like this:
int weekNumber = firstDateOfWeek.getWeekOfWeekyear();
Your date is in week 35.
Humans must not use language of android beings, just kidding, date entering, is another one nail to java coffin.
core of this misunderstanding problem is bad documentation and two facts, months numbered from 0, and year counts from 1900, but not in Calendar and his descendants.
and one more fact, in Date Sunday is 0, but in Calendar Sunday is 1.
//THIS WORKS CORRECTLY
Date my = new Date(1986 - 1900, 04 - 1, 26);
System.out.println(my);
System.out.println(my.getDay());
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
cal.set(1986, 04 - 1, 26);
System.out.println(cal.getTime());
System.out.println(cal.get(Calendar.DAY_OF_WEEK)-Calendar.SUNDAY);
another, much more convenient way
//ONE AND ONLY, HUMAN FRIENDLY WAY TO ENTER DATE INTO JAVA
String date = "1986-04-26:01:23:47";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd:HH:mm:SS");
Date convertedDate = (Date) formatter.parse(date);
System.out.println(convertedDate);
quite simple, is not it?