Android , Calendar.getInstance() not giving the correct month - java

I am trying to write code to find the Day difference between tow date but Calendar.getInstance() keep getting the date for previous month instead of current month
for example :Current 17/7/2014 it get 17/6/2014
my code :
TextView textview=(TextView) findViewById (R.id.textView1);
Calendar cal = Calendar.getInstance();
Calendar startDate=Calendar.getInstance();
startDate.set(Calendar.DAY_OF_MONTH, 1);
startDate.set(Calendar.MONTH,1);
startDate.set(Calendar.YEAR, 2013);
long diff=(((cal.getTimeInMillis()-startDate.getTimeInMillis())/(1000*60*60*24))+1);
String sdiff=String.valueOf(diff);
String stt=cal.get(Calendar.YEAR) +"_"+cal.get(Calendar.MONTH)+"_"+cal.get(Calendar.DAY_OF_MONTH);
textview.setText(stt);

Months start at 0, not at 1, but you really don't have to worry about this if you don't use magic numbers when getting or setting month but instead use the constants. So not this:
startDate.set(Calendar.MONTH,1); // this is February!
but rather
startDate.set(Calendar.MONTH, Calendar.JANUARY);

Months in Java's Calendar start with 0 for January, so July is 6, not 7.
Calendar.MONTH javadocs:
The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0
Add 1 to the result of get.
(cal.get(Calendar.MONTH) + 1)
This also affects your set call. You can either subtract 1 when passing a month number going in, or you can use a Calendar constant, e.g. Calendar.JANUARY.
You can also use a SimpleDateFormat to convert it to your specific format, without having to worry about this quirk.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd");
String stt = sdf.format(cal.getTime());

Related

how does visual foxpro handle date calculation? (comming from java) result for date()-day(date())+1 operation?

what is the correct value for the formula date()-day(date())+1?
if date() returns '2016/5/5'
is it, 2016/5/1? or 2016/4/29?
because when converting code from visual foxpro to java?
following code produces different result.
Calendar today2 = Calendar.getInstance();
Calendar endDate = Calendar.getInstance();
endDate.add(Calendar.DATE, -1 * today2.get(Calendar.DATE));
endDate.add(Calendar.DATE, 1);
above code produces 2016/5/1, while:
Calendar today2 = Calendar.getInstance();
today2.add(Calendar.DATE, 1);
Calendar endDate = Calendar.getInstance();
endDate.add(Calendar.DATE, -1 * today2.get(Calendar.DATE));
above code produces 2016/4/29.
not sure which conversion is correct?
Actually it is obvious and 2016/5/1. Math is simple:
date() - day(date()) would be 2016/5/5 - 5 days which is 2016/4/30 (theDate - day(theDate) gives last day of previous month, adding 1 gives first day of month that theDate is in). Adding 1 day to it means 2016/5/1.
I don't know Java, but to me your 2nd Java code is wrong.
In first one, you are subtracting day of month and then adding 1 (same as what VFP is doing).
In second one, you are setting today2 to "tomorrow", then subtracting tomorrow's day of month from today's date. Which would mean date() - (day(date()+1)) and you would get the day before last month's end date.
Update: I think you can simplify your code as:
Calendar today = Calendar.getInstance();
today.add(Calendar.DATE, 1 - today2.get(Calendar.DATE));
IOW the VFP code to find start of a month:
firstDayOfMonth = theDate - day(theDate) + 1
should translate to:
Calendar firstDayOfMonth = Calendar.getInstance();
firstDayOfMonth.add(Calendar.DATE, 1 - firstDayOfMonth.get(Calendar.DATE));

Finding out what day the first of any given month is

So I need to make a basic calendar which displays the calendar for a specific year and month (the user should be able to select
any month and any year based on text input).
So far, I have managed to create a calender obj, use Scanner to get the desired month and year from the user but my question is that how do I find out what the first day of the month is? In the example above, it's a Saturday. My logic to building it is that if I know the first day, I can make a String[][] array and start displaying the day on the relevant date by looping through the month from the first day. I've used a scanner to get the required month and year. I then created a calendar object and set the Calendar variables; Calendar.YEAR and Calendar.MONTH, as per required by the user:
Calendar cal= Calendar.getInstance();
cal.set(Calendar.YEAR, year); //my year variable is set 2015
cal.set(Calendar.MONTH, chosenMonth); //my chosenMonth is set to 5 since January starts from 0.
I tried using the following code to test out my calender to see if it will execute the code if Monday was the first day of the month. On june 2015, it was.
if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY){
System.out.println("This will print is my calendar secessfully gathers that monday was the first day of the month on June 2015.")
}
It doesn't execute.
Try this:
cal.set(Calendar.DATE, 1);
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("EEEE");
System.out.println(sdf.format(cal.getTime()));
Output:
Saturday
Demo
Java SE 8 has a whole new API for date and time, java.time. See Tutorial.
You can use the class LocalDate to get the day of a given week. For example, using your day from above do,
LocalDate d = LocalDate.of(2011, 10, 1);
Then LocalDate::getDayOfWeek() method will return a DayOfWeek enum instance, such as SATURDAY.
DayOfWeek dayOfWeek = localDate.getDayOfWeek ();
That enum can render a localized string for your sentence output.
String output = dayOfWeek.getDisplayName ( TextStyle.FULL , Locale.CANADA_FRENCH); // Or Locale.US or Locale.ENGLISH, and so on.
samedi

Fetching the first date of a week in java [duplicate]

This question already has answers here:
How to get the first day of the current week and month?
(15 answers)
Closed 6 years ago.
I would like to fetch the first date of a week.
My input is going to be a String type like 07/26/2014".
I need to get the first date of week in which the above date(07/26/2014) falls.
I need output date in MM/dd/YYYY format .
basically I need output as 07/21/2014.
Please give me the java program. I have done upto this
SimpleDateFormat formatter1 = new SimpleDateFormat("MM/dd/yy");
String date ="07/26/2014";
Date Currentdate = formatter1.parse(date);
int currentday=Currentdate.getDay();
Calendar calendar = Calendar.getInstance();
calendar.setTime(Currentdate);
int startDay=currentday-calendar.getFirstDayOfWeek();
Currentdate.setDate(contacteddate.getDate()-startDay);
System.out.println(contacteddate.getDate());
}
The above code only gives me the date.. I need date along with month and year in "MM/dd/YYYY"
Please help
I would do it this way
Calendar calendar = Calendar.getInstance();
calendar.setTime(Currentdate);
calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
After setting time to Calendar
Calendar calendar = Calendar.getInstance();
calendar.setTime(Currentdate);
use
calendar.set(Calendar.DAY_OF_WEEK, 1)
and then
simpleFormat.format(calendar.getTime());
This will help you.
// Get calendar set to current date and time
Calendar c = Calendar.getInstance();
// Set the calendar to monday of the current week
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
// Print dates of the current week starting on Monday
DateFormat df = new SimpleDateFormat("EEE dd/MM/yyyy");
for (int i = 0; i < 1; i++) {
System.out.println(df.format(c.getTime()));
c.add(Calendar.DATE, 1);
}
The problem with all presented solutions so far is not to specify what exactly the week definition is. Week definitions are either technically specified like in ISO-8601-standard (Monday as first day of week and first calendar week of year containing at least four days), or they use localized rules (for example in US a week begins by Sunday!).
Due to the requirement that the OP wants "07/21/2014" as first day of week around "07/26/2014" it seems that ISO-8601 is what the OP really wants. But code like
Calendar calendar = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
...
will not work in a country like US or an application server located in US. Counter example:
// simulating a US-located application server where this code is running
GregorianCalendar calendar = new GregorianCalendar(Locale.US);
calendar.set(2014, Calendar.JULY, 26);
calendar.getTime(); // avoid ugly side effects in calendar date handling
calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(sdf.format(calendar.getTime())); // output: 2014-07-20
If the OP changes the choosen locale to let's say Locale.FRANCE (applying ISO-rules) then the OP can achieve his goal using the traditional Java-date-and-time-library.
It should be noted however that week handling using the java.util.Calendar-stuff is often confusing and hard. For example: Without the strange getter-call (calendar.getTime()) which enforces update of internal calculation the result would be: 2014-07-06 (surely not what OP wants).
Therefore I recommend following other libraries to choose a generic approach compatible with different week definitions:
a) Java-8 (built-in library JSR-310 aka java.time):
LocalDate date = LocalDate.of(2014, 7, 26);
TemporalField dowField = WeekFields.ISO.dayOfWeek();
date = date.with(dowField, dowField.range().getMinimum());
System.out.println(date); // output: 2014-07-21
Note: Avoid code like date.with(DayOfWeek.MONDAY) because in that case the java.time-library cannot evaluate the underlying week rules which possibly deviate from ISO-8601 (here choosen: WeekFields.ISO, but it might also be WeekFields.SUNDAY_START).
b) my own library Time4J:
PlainDate date = PlainDate.of(2014, 7, 26);
date = date.with(Weekmodel.ISO.localDayOfWeek().minimized());
System.out.println(date); // output: 2014-07-21
c) If you know in advance that you only want ISO-8601-week-rules then you might also consider a simpler approach in Java-8 or instead its predecessor JodaTime:
// Java-8 applying ISO-8601-rules
LocalDate date = LocalDate.of(2014, 7, 26);
date = date.with(DayOfWeek.MONDAY);
// Joda-Time
LocalDate date = new LocalDate(2014, 7, 26);
date = date.dayOfWeek().withMinimumValue();

Android Calendar: Changing the start day of week

i have a little problem, i'm developing an application, and i need to change the start day of the week from monday to another one (thursday, of saturday). is this possible in android,
i need to calculate the start to week and its end knowing the date. (the week starts ano thursday as example)
Note: i'm just a beginner in android development.
here is my code
SimpleDateFormat dateformate = new SimpleDateFormat("dd/MM");
// get today and clear time of day
Calendar cal = Calendar.getInstance();
// get start of this week in milliseconds
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
cal.add(Calendar.DAY_OF_YEAR, 7*(WeekIndex-1));
result = dateformate.format(cal.getTime());
cal.add(Calendar.DAY_OF_YEAR, 6 );
result=result+" - " + dateformate.format(cal.getTime());
using the above code im getting the result but with monday as the star of week.
Note: i can't add day to the result because week index changes with the changing of it's start
Calendar days have values 1-7 for days Sunday-Saturday. getFirstDayOfWeek returns one of this values (usually of Monday or Sunday) depending on used Locale. Calendar.getInstance uses default Locale depening on phone's settings, which in your case has Monday as first day of the week.
One solution would be to use other Locale:
Calendar.getInstance(Locale.US).getFirstDayOfWeek()
would return 1, which is value of Calendar.SUNDAY
Other solution would be to use chosen day of week value like
cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
Problem is, Calendar is using its inner first day of the week value in set as well. Example:
Calendar mondayFirst = Calendar.getInstance(Locale.GERMANY); //Locale that has Monday as first day of week
mondayFirst.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
log(DateUtils.formatDateTime(context, mondayFirst.getTimeInMillis(), 0));
//prints "May 19" when runned on May 13
Calendar sundayFirst = Calendar.getInstance(Locale.US); //Locale that has Sunday as first day of week
sundayFirst.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
log(DateUtils.formatDateTime(context, sundayFirst.getTimeInMillis(), 0));
//prints "May 12" when runned on May 13
If you don't want to use Locale or you need other day as the first day of the week, it may be best to calculate start of the week on your own.
GregorianCalendar cal = new GregorianCalendar(yy, currentMonth, 0);
changing the value 0 - starts day from monday
changing the value 1 - starts day from sunday
and so on..
hope this helps and works :)
public int getWeekdayOfMonth(int year, int month){
Calendar cal = Calendar.getInstance();
cal.set(year, month-1, 1);
dayOfWeek = cal.get(Calendar.DAY_OF_WEEK)-1;
return dayOfWeek;
}
weekday = getWeekdayOfMonth();
int day = (weekday - firstweek) < 0 ? (7 - (firstweek - weekday)) : (weekday - firstweek);
"firstweek" means what the start day of you want
then you can calculate the first day you should show.If you have simple method,please tell us. thks
Problem in my case was using Calendar instance returned by MaterialDialog DatePicker, which although having the same Locale as my Calendar.getInstance(Locale...), was having different Calendar.firstDayOfWeek. If you're experiencing the same issue, my workaround was to create new instance of Calendar with my Locale and just changing the property time to the one returned by the DatePicker as following:
val correctCal = Calendar.getInstance(Locale...)?.apply {
time = datePickerCal.time
}
This should return proper Calendar.firstDayOfWeek based on your Locale.

Problems with the Date 31-12-9999 in java

My program needs to represent this date as a java.sql.date object , but it seems that when I create a new date (using the calendar) and set it to '9999-12-31' and finally convert this java.util.date object to a java.sql.date object, this date is converted to something like '000-01-31'.
Calendar calendar = Calendar.getInstance();
calendar.set(9999, 12, 31);
infinityDate = new java.sql.Date(normalizeDate(calendar.getTime()).getTime());
infinityDate should be 31-12-9999
but when my code reaches here :
if(otherDate.equals(infinityDate))
{// Do stuff}
It never goes into the if condition as the infinityDate has for some reason been changed to 31-01-000, even though otherDate is infact '31-12-9999'.
The fact that otherDate is 31-12-9999 tells me that java can represent this dates , but for some reason , when I construct it using a calendar it changes the date. (otherDate comes from a jdbc statement which fetches data from a database)
This reference date '31-12-9999' has been fixed by some client , so it cannot be changed and my program has to be able to compare some incoming date values with this.
Does anyone know why this is happening , I realize that http://en.wikipedia.org/wiki/Year_10,000_problem may be a problem for dates after year 9999 , but I should be safe by a day.
EDIT : The Normalize date method only "normalizes the given date to midnight of that day"
private static java.util.Date normalizeDate(java.util.Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
date = calendar.getTime();
return date;
}
But , this issue was appearing before I was normalizing the date , I normalized it in an attempt to fix this.
Months are zero indexed. Use 11 for December, not 12. This is why you are rolling over the year.
Calendar.MONTH is zero-based. The call
calendar.set(9999, 12, 31);
sets the date to "the 31st day in the 13th month of the year 9999", which is then implicitly converted to the 1st month of the year 10000. It would result in an exception if you first called
calendar.setLenient(false);
Check hours, minutes, seconds and milliseconds that are held into these 2 date objects. I believe they are different.
If your want to compare the date (year, month, day) only you should probably create your custom Comparator and use it.

Categories