Calendar returning the wrong time - java

The time displayed is way ahead of what I expected. I'm parsing a date string and turning it into milliseconds.
year = Integer.parseInt(m1.group(1));
mo = Integer.parseInt(m1.group(2));
day = Integer.parseInt(m1.group(3));
hr = Integer.parseInt(m1.group(4));
min = Integer.parseInt(m1.group(5));
sec = Integer.parseInt(m1.group(6));
and here I set the Calendar
Calendar cal = Calendar.getInstance();
cal.set(year, mo, day, hr, min, sec);
time = cal.getTimeInMillis();

If you check out the calendar documentation here, then visit here, you'll see that January is month 0. You'll want to change your code to mo = Integer.parseInt(m1.group(2))-1;

You should probably use DateFormatter to parse the date string (rather than rolling your own).
Other than that, make sure that you have the proper time zone and understand that month number one is February (not January).

Related

math with dates , + - and ADD

Hello guys i have a tricky question for you that i really cant find a solution out there.
What i want to do is to have 3 date/time inputs on simpledateformat
Date 1
Date 2
Date 3
and basicaly i want to get difference of months days hours and minutes from date 1 - date2 and result of those 2 dates to be added on the firth date
for example 11/3/2017 12:30 - 7/3/2017 = 4 days and ADD that to current date 13/3/2017 13:30 + 4 days and 1 hour = 17/3/2017 14:30
i know how to get the diference in days hours and minutes , i cant get the second part of adding the result to the current date
any ideas?
thank you in dvance
Use Calendar class to add days and hours
Calendar cal = Calendar.getInstance();
cal.setTime(yourDate);
cal.add(Calendar.DAY_OF_MONTH, yourDays); //adds days to your date
cal.add(Calendar.HOUR_OF_DAY, yourHours); //adds hours to your date
cal.getTime(); //to get Date instance
To decrement dates just add negative number, for example:
int yourDays = -daysVariable;
int yourHours = -hoursVariable; //
Calendar cal = Calendar.getInstance();
cal.setTime(yourDate);
cal.add(Calendar.DAY_OF_MONTH, yourDays); //decrement days
cal.add(Calendar.HOUR_OF_DAY, yourHours); //decrement hours
cal.getTime(); //to get Date instance
Get a date object using the simpledate format
Because it is an object of the same type
Comparison is possible
I think you need to use getTime and add days throught miliseconds.
For example, if you can get the difference of days you should use something like this
date1.getTime() + 24*60*60*1000*4
(where 4 is the difference you want to add)
You can use Calendar too.
Thank you all for your ultra fast replies!
I solved it by using Mij Solution
Calendar cal = Calendar.getInstance();
cal.setTime(yourDate);
cal.add(Calendar.DAY_OF_MONTH, yourDays); //adds days to your date
cal.add(Calendar.HOUR_OF_DAY, yourHours); //adds hours to your date
cal.getTime(); //to get Date instance
To add days and
tis code to decrese days
Calendar cal = Calendar.getInstance();
cal.setTime(yourDate);
cal.add(Calendar.DAY_OF_MONTH, -yourDays); //adds days to your date
cal.add(Calendar.HOUR_OF_DAY, -yourHours); //adds hours to your date
cal.getTime(); //to get Date instance
and to control if date is bigget than my current date i used this condition
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(valid_until);
if (new Date().after(strDate)) {
catalog_outdated = 1;
}
it returns -1 if the date is past from current
+1 if date is bigger that current or whatever
and 0 if dates are equal
again thank you!

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

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

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.

Android get difference in milliseconds between two dates

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.

Compare same date using java

The date is selected by the user using a drop down for year, month and day. I have to compare the user entered date with today's date. Basically see if they are the same date. For example
the user entered 02/16/2012. And if today is 02/16/2012 then I have to display a message. How do I do it?
I tried using milliseconds but that gives out wrong results.
And what kind of object are you getting back? String, Calendar, Date? You can get that string and compare it, at least that you think you'll have problems with order YYYY MM DD /// DD MM YYY in that case I suggest to create a custom string based on your spec YYYYMMDD and then compare them.
Date d1 = new Date();
Date d2 = new Date();
String day1 = d1.getYear()+"/"+d1.getMonth()+"/"+d1.getDate();
String day2 = d2.getYear()+"/"+d2.getMonth()+"/"+d2.getDate();
if(day1.equals(day2)){
System.out.println("Same day");
}
Dates in java are moments in time, with a resolution of "to the millisecond". To compare two dates effectively, you need to first set both dates to the "same time" in hours, minutes, seconds, and milliseconds. All of the "setTime" methods in a java.util.Date are depricated, because they don't function correctly for the internationalization and localization concerns.
To "fix" this, a new class was introduced GregorianCalendar
GregorianCalendar cal1 = new GregorianCalendar(2012, 11, 17);
GregorianCalendar cal2 = new GregorianCalendar(2012, 11, 17);
return cal1.equals(cal2); // will return true
The reason that GregorianCalendar works is related to the hours, minutes, seconds, and milliseconds being initialized to zero in the year, month, day constructor. You can attempt to approximate such with java.util.Date by using deprecated methods like setHours(0); however, eventually this will fail due to a lack of setMillis(0). This means that to use the Date format, you need to grab the milliseconds and perform some integer math to set the milliseconds to zero.
date1.setHours(0);
date1.setMinutes(0);
date1.setSeconds(0);
date1.setTime((date1.getTime() / 1000L) * 1000L);
date2.setHours(0);
date2.setMinutes(0);
date2.setSeconds(0);
date2.setTime((date2.getTime() / 1000L) * 1000L);
return date1.equals(date2); // now should do a calendar date only match
Trust me, just use the Calendar / GregorianCalendar class, it's the way forward (until Java adopts something more sophisticated, like joda time.
There is two way you can do it. first one is format both the date in same date format or handle date in string format.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String date1 = sdf.format(selectedDate);
String date2 = sdf.format(compareDate);
if(date1.equals(date2)){
}else{
}
Or
Calendar toDate = Calendar.getInstance();
Calendar nowDate = Calendar.getInstance();
toDate.set(<set-year>,<set-month>,<set-date->);
if(!toDate.before(nowDate))
//display your report
else
// don't display the report
Above answers are correct but consider using JodaTime - its much simpler and intuitive API.
You could set DateTime using with* methods and compare them.
Look at this answer

Categories