I build an android calendar example, but I am weird when I worked with it.
I tried to get Monday this week which I set. However, within this code
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DATE, day);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
int start = calendar.get(Calendar.DAY_OF_MONTH);
I cannot get right activity. A symptom is I can get right Monday of this week
but last week also gave me this monday, so I tried another code which is
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DATE, day);
int start = calendar.get(Calendar.DATE);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
start = calendar.get(Calendar.DATE);
Then I can get right activity what I want.
However I do not know why it is working and difference between these two codes.
Thanks for reading and helping!
First importan info,calendar has two modes for interpreting the calendar fields, lenient and non-lenient.
When a Calendar is in lenient mode, it accepts a wider range of calendar field values than it produces. When a Calendar recomputes calendar field values for return by get(), all of the calendar fields are normalized. For example, a lenient GregorianCalendar interprets MONTH == JANUARY, DAY_OF_MONTH == 32 as February 1.
When a Calendar is in non-lenient mode, it throws an exception if there is any inconsistency in its calendar fields. For example, a GregorianCalendar always produces DAY_OF_MONTH values between 1 and the length of the month. A non-lenient GregorianCalendar throws an exception upon calculating its time or calendar field values if any out-of-range field value has been set.
Another important info,calendar set method is only set the field value,but not update time and compute every fields(like year,month,day and so on) until you use any get method.
When Calendar run in lenient mode,here is code:
Calendar calendar = Calendar.getInstance();
calendar.setLenient(true);
calendar.set(Calendar.DATE, 1);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println(calendar.get(Calendar.DAY_OF_MONTH));
code run result is 10.
After call two set mothed, begin call get Calendar.DAY_OF_MONTH,now calendar begin to update time , Date 1 and DAY_OF_WEEK of MONDAY confuse , but Calendar is in lenient mode, final calculate the date 2016-10-10,so get result is 10.
same code in non-lenient mode:
Calendar calendar = Calendar.getInstance();
calendar.setLenient(false);
calendar.set(Calendar.DATE, 1);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println(calendar.get(Calendar.DAY_OF_MONTH));
throws java.lang.IllegalArgumentException: DAY_OF_MONTH exception.
last code:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DATE, 1);
int start = calendar.get(Calendar.DATE);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
start = calendar.get(Calendar.DATE);
code run result is 26.
when first call get Calendar.DATE,this call will updatetime and compute every fields . calculate date is 2016-10-01 .then call set(Calendar.DAY_OF_WEEK, Calendar.MONDAY), after this call get method,calculate date is 2016-09-26,so result is 26.
Related
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));
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());
I have Integer fields:
currentYear,currentMonth,currentDay,currentHour,currentMinute and nextYear,nextMonth,nextDay,nextHour,nextMinute.
How I can get difference between those two spots in time in milliseconds.
I found a way using Date() object, but those functions seems to be depricated, so it's little risky.
Any other way?
Use GregorianCalendar to create the date, and take the diff as you otherwise would.
GregorianCalendar currentDay=new GregorianCalendar (currentYear,currentMonth,currentDay,currentHour,currentMinute,0);
GregorianCalendar nextDay=new GregorianCalendar (nextYear,nextMonth,nextDay,nextHour,nextMinute,0);
diff_in_ms=nextDay. getTimeInMillis()-currentDay. getTimeInMillis();
Create a Calendar object for currenDay and nextDay, turn them into longs, then subtract. For example:
Calendar currentDate = Calendar.getInstance();
Calendar.set(Calendar.MONTH, currentMonth - 1); // January is 0, Feb is 1, etc.
Calendar.set(Calendar.DATE, currentDay);
// set the year, hour, minute, second, and millisecond
long currentDateInMillis = currentDate.getTimeInMillis();
Calendar nextDate = Calendar.getInstance();
// set the month, date, year, hour, minute, second, and millisecond
long nextDateInMillis = nextDate.getTimeInMillis();
return nextDateInMillis - currentDateInMillis; // this is what you want
If you don't like the confusion around the Calendar class, you can check out the Joda time library.
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.
The posters here say that Date is always in UTC time. However, if I create a Date(), create a Calendar, and set the calendar time with the date, the time remains my local time (and I am not on UTC time.
I've tested this by printing out the calendar's date in a loop, subtracting an hour per loop. It's 11pm on the 19th of May here, and it takes 24 loops before the date changes to the 18th of May. It's currently 1pm UTC, so if the calendar were set properly it would only take 14 loops.
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
int index = 0;
for(; index > -30; index--)
{
System.out.println(index);
System.out.println(dateFormatter.format(calendar.getTime()));
System.out.println();
calendar.add(Calendar.HOUR, -1);
}
java.util.Calendar has a static factory method which takes a timezone.
Calendar.getInstance(java.util.TimeZone)
So you can say:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));