Why does this code generate incorrect data? - java

I have this code in my project
Calendar subval = Calendar.getInstance();
final int WOY= subval.WEEK_OF_YEAR;
and when I check it for value of WOY it outputs 3 now it is currently Feb 25 2013 and I know the week number is not three. I am storing this value to help set automatic refresh times so I am able to force a refresh to make sure the device has the most current data. In between refresh periods some crucial data is stored locally. Now I need a reliable fixed time slot and I chose once a week basically if the WEEK OF YEAR is not the same as the stored value for WEEK OF YEAR set data to be refreshed at next opportunity and then store current WEEK OF YEAR on device. I started coding this within 1 week so I have not transitioned to the new week so I am not sure if it working correctly but the value of three scares me.

WEEK_OF_YEAR is a flag used to the get() method. It's value never changes.
You use it like this:
Calendar subval = Calendar.getInstance();
final int WOY= subval.get(Calendar.WEEK_OF_YEAR);

Calendar.WEEK_OF_YEAR is a constant to be used to specify which field to return from your Calendar instance. Instead of assigning the value to the fixed value, you need to call Calendar#get:
int WOY = subval.get(Calendar.WEEK_OF_YEAR);

You need to get it like this
Calendar subval = Calendar.getInstance();
int year=subval.get(Calender.Calendar.WEEK_OF_YEAR);

Calendar.WEEK_OF_YEAR is a static constant.
You need to call calendar.get(Calendar.WEEK_OF_YEAR)

Subclasses define WEEK_OF_YEAR for days before the first week of year according to the java oracle documentation
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Calendar.html
see: week_of_year

Related

Java app to get time from local machine time

I am developing a java system that will keep track of a certain company's fixed assets, calculate the depreciating value using the straight line accounting method so the depreciating value will always be constant. after calculating all this it should divide the figure by 12 to get a monthly depreciating value and then alert the user (finance) of the depreciating after every financial year. how can I make the java based app get the time from the local machine to trigger these alerts.
First set the financial year of your app to, for instance, (31/03/2015) and then compare with the current date from your local machine. Check out the code for clarity:
if(getCurrentDate().equals((31/03/2015))||getCurrentDate().after((31/03/2015))){
//then do something here
}
And here is the method to get current date:
public static java.util.Date getCurrentDate() {
int month = GregorianCalendar.getInstance().get(Calendar.MONTH);
int year = GregorianCalendar.getInstance().get(Calendar.YEAR);
int day = GregorianCalendar.getInstance().get(Calendar.DATE);
Calendar calender = Calendar.getInstance();
calender.set(year, month, day);
return calender.getTime();
}

In which type of variable store time in millis? Choosing a correct data type

in Java I'm trying to compare two different hours by converting them to milliseconds if (20:00 > 19:30) // do anything. In millis, it would be if (72000000 > 70200000) // do anything
But the smartphone doesn't do it well. I'm storing the numbers in variables long, as in the class Calendar, the method myCal.getTimeInMillis() returns a long, but it doesn't work.
I have tried changing the data type of the variables from long to double and it does work, so I figure out that those large numbers simply "doesn't fit" in the variable, but then, why the Java Calendar method getTimeInMillis() returns a long?
How does time work in Java Calendar? Thanks in advance.
Edit:
Thank you for your answers and time, I'm sorry for this question because it does work to compare different hours which are stored in long variables. I have tried again and it does work (I don't know why it didn't work before). I'm making an alarm clock app for Android and I want to compare not only two hours (and minutes and seconds), but also day of the week and so on. So I'm going to mark as the solution of this question the answer of #Sufiyan Ghori because I think it can really help me, and I think I'm gonna delete this question because it has no sense.
I'm new here (and in programming in general), so sorry for this silly question.
instead of comparing hours after converting it into milliseconds you can use Date::before or Date::after methods after setting your time into two separate Date objects.
Date date1 = new Date(); // set time for first hour.
Date date2 = new Date(); // set time for second hour.
You can use Calendar to set time for each Date object, like this,
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY,12);
cal.set(Calendar.MINUTE,10);
cal.set(Calendar.SECOND,31);
cal.set(Calendar.MILLISECOND,05);
date1 = cal.getTime(); //set time for first hour
and then use these for comparison,
if(date1.after(date2)){
}
if(date1.before(date2)){
}
and Date::equals,
if(date1.equals(date2)){
}
getTimeInMillis() doesn't return milliseconds passed from the start of the current day, it returns millisecons passed since 01 Jan 1970 00:00:00 GMT.
Take a look at documentation of Calendar class: java.util.Calendar

Only default values are returned in Calendar object in android. Why?

I have set a date to a calendar object in this way...
Calendar lastCheckUp = Calendar.getInstance();
lastCheckUp.set(year, month+1, day);
Now, when I print this out in the console using
System.out.println(lastCheckUp);
I get the correct values...
07-18 11:59:13.903: I/System.out(1717): java.util.GregorianCalendar[time=1365834504001,areFieldsSet=true,lenient=true,zone=Asia/Calcutta,firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2013,MONTH=3,WEEK_OF_YEAR=15,WEEK_OF_MONTH=2,DAY_OF_MONTH=13,DAY_OF_YEAR=103,DAY_OF_WEEK=7,DAY_OF_WEEK_IN_MONTH=2,AM_PM=0,HOUR=11,HOUR_OF_DAY=11,MINUTE=58,SECOND=24,MILLISECOND=1,ZONE_OFFSET=19800000,DST_OFFSET=0]
So i'm assuming that all the values are set correctly in the calendar object.
But when I try to access it using
mTextViewLastCheckDate.setText(new StringBuilder().append(lastCheckUp.DAY_OF_MONTH)
.append("/").append(lastCheckUp.MONTH).append("/").append(lastCheckUp.YEAR)
.append(" "));
I get only the default values...
That is, my textview gives an output of 5/2/1
What am i doing wrong?
You're using lastCheckup.MONTH, lastCheckup.DAY_OF_MONTH etc. Those are constant fields - to access the values for a specific calendar, you need
int month = lastCheckUp.get(Calendar.MONTH);
etc. Read the documentation of Calendar for more details about how you're meant to use it.
However, you would also need to understand that months are 0-based in Calendar, so it still wouldn't look right. Also, you almost certainly want to 0-pad the day and month. You'd be much better off using SimpleDateFormat to do this for you.
// Not sure why you want a space at the end, but...
DateFormat format = new SimpleDateFormat("dd/MM/yyyy ");
mTextViewLastCheckDate.setText(format.format(lastCheckup.getTime());
You should consider which time zone and locale you want to use, too. The above code just uses the default.
EDIT: Note that this line:
lastCheckUp.set(year, month+1, day);
is almost certainly wrong. We don't know what month is really meant to be here, but in the set call it should be in the range 0-11 inclusive (assuming a Gregorian calendar).
Your problem is how you are accessing the Calendar's get method and your reference to Calendar constants.
Try this:
mTextViewLastCheckDate.setText(
new StringBuilder().append(lastCheckUp.get(Calendar.DAY_OF_MONTH))
.append("/")
.append(lastCheckUp.get(Calendar.MONTH)) // beware, Calendar months are 0 based
// please refer to Jon Skeet's solution for a better print out of your date
// or add +1 to the month value here, instead of setting your Calendar with month + 1.
// Otherwise December will not work. See also comments below.
.append("/")
.append(lastCheckUp.get(Calendar.YEAR))
.append(" ")
);
By the way, most IDEs will warn you when you are trying to access a class' constants from an instance of said class.
This can help you figure out what you're doing wrong usually.

How can I iterate through an array once per day?

So I'm working on an application that needs to display a value, a specific string of text once per day. I have all my strings in an array and now I just need a way to increase the index once per day. The kicker is that if the user downloads the application later in the year I need to have all the other days accounted for. So basically the user will see the same tip as a person who downloaded the app on the first day. Any suggestions?
Would using the Calendar class be my best bet? I just don't want to set an individual switch and case for every day of the year.
Not sure if I understand completely the question. I think you will need to have the same tip shown for everyone in each day, right?
If so, you can use Calendar.DAY_OF YEAR :
Calendar cal = Calendar.getInstance();
int index=cal.get(Calendar.DAY_OF_YEAR);
if I understand you correctly (Bob downloaded the app a hundred days ago should see the same tip as Alice who downloaded the application today), you can use Calendar's DAY_OF_YEAR value to display the same date
Calendar ca1 = Calendar.getInstance(); //get today's date
int DAY_OF_YEAR=ca1.get(Calendar.DAY_OF_YEAR) -1; //DAY_OF_YEAR starts at one
//avoid IndexOutOfBoundsExceptions
String tip = tiparray[DAY_OF_YEAR % tiparray.length];

Working with Date and Calendar

I have a datepicker where the user selects a date and then a checkbox on what type of period he wants to get the date from. For example:
User selects the 1. of November and selects the checkbox "Month" in this case the end date will be increased by 1 and even if this sound simple enough its slowly starting to annoy me alot!
The problem is that Java doesnt have a great date object that works for this kind of thing so i thought that i would use Calendar but it isnt easy to increment a calendar date take for instance the following example:
endDate.set(startDate.YEAR, startDate.MONTH+1, startDate.DATE);
in theory this would increment the month by one being one larger than the start date. This works in about 90 % of the months EXECPT from December if you increase the month by 1 in December then the integer month return 13 same thing happens for startDate.DATE; and startDate.Year;
My question is isnt there an easier way to do this? i could make a ton of If sentences but i really think that it is kinda redundant.
Use add method of java.util.Calendar.
endDate.set(startDate.YEAR, startDate.MONTH, startDate.DATE);
if(some_condition) {
endDate.add(Calendar.MONTH, 1);
}
You can use Calendar.add() to add values to the calendar value, e.g. Calendar.add(Calendar.MONTH, 1) this adds one month and takes into account that January is after December.
The standard recomendation here is to look at Joda-Time (see here for more info). It's a much more consistent/capable API with none of the threading issues that plague the standard Java date/formatting APIs and as such is widely used and accepted.
In terms of what you want above, I would suggest something like:
LocalDate d = ...
LocalDate nd = d.plusMonths(1);
The above will correctly handle month/year rollovers.

Categories

Resources