Android Calendar problem with day of the week - java

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?

Related

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

Creating a DateTime from two other dates

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

java.util.Date and getYear()

I am having the following problem in Java (I see some people are having
a similar problem in JavaScript but I'm using Java)
System.out.println(new Date().getYear());
System.out.println(new GregorianCalendar().getTime().getYear());
System.out.println(this.sale.getSaleDate().getYear());
System.out.println(this.sale.getSaleDate().getMonth());
System.out.println(this.sale.getSaleDate().getDate());
returns
I/System.out( 4274): 112
I/System.out( 4274): 112
I/System.out( 4274): 112
I/System.out( 4274): 1
I/System.out( 4274): 11
I don't understand the 112 bit which I thought would have been 2012.
What's going on? Is the
java.util.Date class unusable? I am storing this as a field in several
of my classes to store a date and time. What should I do?
In addition to all the comments, I thought I might add some code on how to use java.util.Date, java.util.Calendar and java.util.GregorianCalendar according to the javadoc.
//Initialize your Date however you like it.
Date date = new Date();
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
//Add one to month {0 - 11}
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
According to javadocs:
#Deprecated
public int getYear()
Deprecated. As of JDK version 1.1, replaced by Calendar.get(Calendar.YEAR) - 1900.
Returns a value that is the result of subtracting 1900 from the year that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.
Returns:
the year represented by this date, minus 1900.
See Also:
Calendar
So 112 is the correct output. I would follow the advice in the Javadoc or use JodaTime instead.
Use date format
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse(datetime);
SimpleDateFormat df = new SimpleDateFormat("yyyy");
year = df.format(date);
Don't use Date, use Calendar:
// Beware: months are zero-based and no out of range errors are reported
Calendar date = new GregorianCalendar(2012, 9, 5);
int year = date.get(Calendar.YEAR); // 2012
int month = date.get(Calendar.MONTH); // 9 - October!!!
int day = date.get(Calendar.DAY_OF_MONTH); // 5
It supports time as well:
Calendar dateTime = new GregorianCalendar(2012, 3, 4, 15, 16, 17);
int hour = dateTime.get(Calendar.HOUR_OF_DAY); // 15
int minute = dateTime.get(Calendar.MINUTE); // 16
int second = dateTime.get(Calendar.SECOND); // 17
The java documentation suggests to make use of Calendar class instead of this deprecated way
Here is the sample code to set up the calendar object
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
Here is the sample code to get the year, month, etc.
System.out.println(calendar.get(Calendar.YEAR));
System.out.println(calendar.get(Calendar.MONTH));
Calendar also has support for many other useful information like, TIME, DAY_OF_MONTH, etc. Here the documentation listing all of them
Please note that the month are 0 based. January is 0th month.
tl;dr
LocalDate.now() // Capture the date-only value current in the JVM’s current default time zone.
.getYear() // Extract the year number from that date.
2018
java.time
Both the java.util.Date and java.util.Calendar classes are legacy, now supplanted by the java.time framework built into Java 8 and later.
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( "Africa/Tunis" ) ;
If you want only the date without time-of-day, use LocalDate. This class lacks time zone info but you can specify a time zone to determine the current date.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate localDate = LocalDate.now( zoneId );
You can get the various pieces of information with getYear, getMonth, and getDayOfMonth. You will actually get the year number with java.time!
int year = localDate.getYear();
2016
If you want a date-time instead of just a date, use ZonedDateTime class.
ZonedDateTime zdt = ZonedDateTime.now( zoneId ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.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.
Much of the java.time functionality is back-ported to Java 6 & Java 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (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.
Yup, this is in fact what's happening. See also the Javadoc:
Returns:
the year represented by this date, minus 1900.
The getYear method is deprecated for this reason. So, don't use it.
Note also that getMonth returns a number between 0 and 11. Therefore, this.sale.getSaleDate().getMonth() returns 1 for February, instead of 2. While java.util.Calendar doesn't add 1900 to all years, it does suffer from the off-by-one-month problem.
You're much better off using JodaTime.
Java 8 LocalDate class is another option to get the year from a java.util.Date,
int year = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date)).getYear();
Another option is,
int year = Integer.parseInt(new SimpleDateFormat("yyyy").format(date));
There are may ways of getting day, month and year in java.
You may use any-
Date date1 = new Date();
String mmddyyyy1 = new SimpleDateFormat("MM-dd-yyyy").format(date1);
System.out.println("Formatted Date 1: " + mmddyyyy1);
Date date2 = new Date();
Calendar calendar1 = new GregorianCalendar();
calendar1.setTime(date2);
int day1 = calendar1.get(Calendar.DAY_OF_MONTH);
int month1 = calendar1.get(Calendar.MONTH) + 1; // {0 - 11}
int year1 = calendar1.get(Calendar.YEAR);
String mmddyyyy2 = ((month1<10)?"0"+month1:month1) + "-" + ((day1<10)?"0"+day1:day1) + "-" + (year1);
System.out.println("Formatted Date 2: " + mmddyyyy2);
LocalDateTime ldt1 = LocalDateTime.now();
DateTimeFormatter format1 = DateTimeFormatter.ofPattern("MM-dd-yyyy");
String mmddyyyy3 = ldt1.format(format1);
System.out.println("Formatted Date 3: " + mmddyyyy3);
LocalDateTime ldt2 = LocalDateTime.now();
int day2 = ldt2.getDayOfMonth();
int mont2= ldt2.getMonthValue();
int year2= ldt2.getYear();
String mmddyyyy4 = ((mont2<10)?"0"+mont2:mont2) + "-" + ((day2<10)?"0"+day2:day2) + "-" + (year2);
System.out.println("Formatted Date 4: " + mmddyyyy4);
LocalDateTime ldt3 = LocalDateTime.of(2020, 6, 11, 14, 30); // int year, int month, int dayOfMonth, int hour, int minute
DateTimeFormatter format2 = DateTimeFormatter.ofPattern("MM-dd-yyyy");
String mmddyyyy5 = ldt3.format(format2);
System.out.println("Formatted Date 5: " + mmddyyyy5);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(new Date());
int day3 = calendar2.get(Calendar.DAY_OF_MONTH); // OR Calendar.DATE
int month3= calendar2.get(Calendar.MONTH) + 1;
int year3 = calendar2.get(Calendar.YEAR);
String mmddyyyy6 = ((month3<10)?"0"+month3:month3) + "-" + ((day3<10)?"0"+day3:day3) + "-" + (year3);
System.out.println("Formatted Date 6: " + mmddyyyy6);
Date date3 = new Date();
LocalDate ld1 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date3)); // Accepts only yyyy-MM-dd
int day4 = ld1.getDayOfMonth();
int month4= ld1.getMonthValue();
int year4 = ld1.getYear();
String mmddyyyy7 = ((month4<10)?"0"+month4:month4) + "-" + ((day4<10)?"0"+day4:day4) + "-" + (year4);
System.out.println("Formatted Date 7: " + mmddyyyy7);
Date date4 = new Date();
int day5 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getDayOfMonth();
int month5 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getMonthValue();
int year5 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getYear();
String mmddyyyy8 = ((month5<10)?"0"+month5:month5) + "-" + ((day5<10)?"0"+day5:day5) + "-" + (year5);
System.out.println("Formatted Date 8: " + mmddyyyy8);
Date date5 = new Date();
int day6 = Integer.parseInt(new SimpleDateFormat("dd").format(date5));
int month6 = Integer.parseInt(new SimpleDateFormat("MM").format(date5));
int year6 = Integer.parseInt(new SimpleDateFormat("yyyy").format(date5));
String mmddyyyy9 = ((month6<10)?"0"+month6:month6) + "-" + ((day6<10)?"0"+day6:day6) + "-" + (year6);
System.out.println("Formatted Date 9: " + mmddyyyy9);
Year.now()
There's an easier way to use the java.time library in Java 8+. The expression:
java.time.Year.now().getValue()
returns the current year as a four-digit int, using your default time zone. There are lots of options for different time ZoneIds, Calendars and Clocks, but I think this is what you will want most of the time. If you want the code to look cleaner (and don't need any other java.time.*.now() functions), put:
import static java.time.Year.now;
at the top of your file, and call:
now().getValue()
as needed.
This behavior is documented in the java.util.Date -class documentation:
Returns a value that is the result of subtracting 1900 from the year
that contains or begins with the instant in time represented by this
Date object, as interpreted in the local time zone.
It is also marked as deprecated. Use java.util.Calendar instead.
try{
int year = Integer.parseInt(new Date().toString().split("-")[0]);
}
catch(NumberFormatException e){
}
Much of Date is deprecated.

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

extract day from Date

I receive a timestamp from a SOAP service in milliseconds. So I do this:
Date date = new Date( mar.getEventDate() );
How can I extract the day of the month from date, since methods such as Date::getDay() are deprecated?
I am using a small hack, but I do not think this is the proper way to obtain day-of-month.
SimpleDateFormat sdf = new SimpleDateFormat( "dd" );
int day = Integer.parseInt( sdf.format( date ) );
Use Calendar for this:
Calendar cal = Calendar.getInstance();
cal.setTime(mar.getEventDate());
int day = cal.get(Calendar.DAY_OF_MONTH);
Update: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. See Tutorial by Oracle.
See the correct Answer by Ortomala Lokni, using the modern java.time classes. I am leaving this outmoded Answer intact as history.
The Answer by Lokni is correct.
Here is the same idea but using Joda-Time 2.8.
long millisSinceEpoch = mar.getEventDate() ;
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" ) ; // Or DateTimeZone.UTC
LocalDate localDate = new LocalDate( millisSinceEpoch , zone ) ;
int dayOfMonth = localDate.getDayOfMonth() ;
Given the Date constructor used in the question
Date date = new Date(mar.getEventDate());
The method mar.getEventDate() returns a long that represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.
Java 8 and later
In Java 8, you can extract the day of the month from this value, assuming UTC, with
LocalDateTime.ofEpochSecond(mar.getEventDate(),0,ZoneOffset.UTC).getDayOfMonth();
Note also that the answer given by cletus assume that mar.getEventDate() returns a Date object which is not the case in the question.

Categories

Resources