I'm confused about how a Gregorian Calendar associates days with numbers. For examples, I instantiate an object
GregorianCalendar cal = new GregorianCalendar();
Toast.makeText(context, "Day: " + cal.DAY_OF_WEEK, Toast.LENGTH_LONG).show();
My toast messages keeps dispalying "Day: 7"
Today is Friday, assuming that Sunday = 0, shouldn't the text display "Day: 5"?
It does work when I do the following:
int current day = cal.get(Calendar.DAY_OF_WEEK)
Can someone explain why? Thank you.
The reason that you're getting a 7 with cal.DAY_OF_WEEK, is that you're actually asking for the value of the constant named DAY_OF_WEEK and the value of that field is 7. See here. In other words, cal.DAY_OF_WEEK is really equivalent to Calendar.DAY_OF_WEEK.
You get the correct answer with cal.get(Calendar.DAY_OF_WEEK), because you're then asking for the value of cal's DAY_OF_WEEK field.
Related
For an easteregg in my Android app, I have to compare the current date with a stored date - and I only need to know if it's the right month.
I know that System.currentTimeMillis() is the fastest way to get the current time but now I need to get the current month from that. I avoided String comparison for it's known flaws.
My awful implementation works but it really doesn't look correct and efficient:
if (Integer.parseInt((String) DateFormat.format("MM",System.currentTimeMillis()))==12) //xmas "easteregg"
xmasBool=true;
Is there any more elegant solution for this?
Here's a better solution:
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date()); // Date's default constructor gives you current time
xmasBool = calendar.get(Calendar.MONTH) == Calendar.DECEMBER;
Calendar c = Calendar.getInstance();
int month = c.get(Calendar.MONTH);
And now you can compare the variable month with your stored month.
You can compare a day or a month or both, the whole date by formatting java.Util.Date using SimpleDateFormat.
Eg.
new SimpleDateFormat("dd").format(new java.util.Date())
gives you the "day" value. Similarly "MM" will give you the month. Use combination of those as per your requirement.
Store it in the same format and you have a common standard for comparison.
I´ve been trying to figure this out for a while but can not wrap my head around it.
I´m working on an android app and i want to display left to a specific date, and i want the number of days based on what time zone i have set on my phone.
I have Joda Time in my app and the information i have is for example:
2013-05-05 9.00PM the time is in PST (GMT-8) timezone, i have no clue how to do this and i have searched both on google and SO but can not get a clear answer.
EDIT
I managed to solve my problem with code found here on SO
String dateString = airDate + " " + airTime.toUpperCase();
SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd K:mma");
sourceFormat.setTimeZone(TimeZone.getTimeZone("GMT-8"));
Date parsed;
parsed = sourceFormat.parse(dateString);
TimeZone tz = TimeZone.getDefault();
SimpleDateFormat destFormat = new SimpleDateFormat("yyyy-MM-dd");
destFormat.setTimeZone(tz);
result = destFormat.format(parsed);
However I found out that the times i first got isn´t correct and I now get the time zone in the format GMT-5 +DST. And I dont´t know what to do with the +DST if setting the time to 20:00 and using GMT-5 in my TimeZone.getTimeZone the time returned is 22:00 which is "wrong" since I live in sweden. I would appreciate any help with this.
If you could settle for a string that looks like "in 2 days", then you should be able to use DateUtils.getRelativeTimeSpanString().
I wrote some code that I am try to use as a comparison for a subscription so this piece of code was supposed to dump the current date. The month and day are correct but the year is off by about 1900 or so any ideas as to why
Calendar calendar=Calendar.getInstance();
Date validDate = new Date(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
complain(validDate.toString());
complain is a function I wrote to simply the dump the value of a string to the screen in an alert box
It shows this 3913-02-10
I need to get this fixed before I start doing comparisons so the quicker the better
OK I added some new code and not using the depracated Date any longer but now my month is of by 1 it shows 2013 1 10
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
complain(String.valueOf(year) + " " + String.valueOf(month) + " " + String.valueOf(day));
After further research I found that MONTH returns the correct value but I have to say this is VERY unintuitive I would think that it would coincide with normal understandings of the date format
This has January set to 0, February to 1, March to 2, etc. it is non intuitive.
Thanks to all
You are using a deprecated constructor that takes the year - 1900 as its first argument.
Depending on what you're gonna end up doing with the app, take this with a grain of salt:
Just subtract 1900 from the year and send that to your method or whatever you're doing.
Note: THIS IS A TERRIBLE PROGRAMMING PRACTICE and if this is anything other than self-education, FIND A BETTER WAY.
I am trying to display in a TextView when my application last updated (e.g., "Last updated at 12:13). I am trying to use a Calendar instance and I thought I understood it correctly but I seem to be having trouble. I know to get an instance I use the method Calendar.getInstance(). And then to get the hour and minute I was using Calendar.get(Calendar.HOUR) and Calendar.get(Calendar.MINUTE). My minute field returns correctly but Calendar.HOUR is returning the hour on a 24 hour clock and I want a 12 hour clock. I thought HOUR_OF_DAY was 24 hour clock. Where am I going wrong?
Here is the code I'm using:
Calendar rightNow = Calendar.getInstance();
mTv.setText("Refreshed! Last updated " +
rightNow.get(Calendar.HOUR) + ":" +
rightNow.get(Calendar.MINUTE) + ".");
mTv is my TextView that I'm updating. Thanks for any help.
Also, it would be ideal if I could say "Last updated 5 minutes ago." instead of "Last updated at 12:13pm". But I'm not sure the best way to have this update each minute without draining resources or the battery...?
I'd recommend using SimpleDateFormat in combination with the Date class for formatting the time:
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("K:mm a");
String formattedTime = sdf.format(now);
Short explanation how it works:
You create a SimpleDateFormat object and pass a String to it's construtor which tells it how to format every time/date object that gets passed to the format() function of it.
There are plenty of constants/letters which represent a special time object (e.g. seconds, an AM/PM marker, .. see the class documentation for the full list).
"K:mm a" means a "11:42 AM" format - one or two digits for the hour (depending on its value) in a 12 hour format, always two digits for minutes (mm) and either AM or PM (a), depending on the time.
After you did that, just pass a Date object to the format() function, and you'll get a formatted string. Note that a Date just holds one single point in time, if you create it from the constructor with no arguments ("= new Date()") it uses the current time. If you need another time, you can pass a long argument with the millis, you may get that from Calendar.getTimeInMillis().
As of implementing the "updated XY minutes ago function" - yes you'd have to update this every minute and you have to calculate the difference between the update and the current time. I'd say it's not worth it from a battery and extra work perspective.
If your app uses standard short update cycles (e.g. every hour or somthing along those lines) and is not fullscreen, the user has a visible clock on top/bottom of his screen. If he really wants to check how long it was since the update, he can take a short look and compare (mostly just minutes or hours/minutes). And IMHO thats no inconvinience for a user, at least it would not for me. I'd just compare without thinking about that. But I tend to kill apps which waste my battery for no useful reason.
Also note that not everybody uses a 12-hour format. To get a localized time format depending on users settings/country use DateFormat.getTimeInstance(). This returns a DateFormat, but this works like the SimpleDateFormat, just pass a time to format().
Use Calendar.HOUR_OF_DAY for 24h clock
Calendar rightNow = Calendar.getInstance();
mTv.setText("Refreshed! Last updated " +
rightNow.get(Calendar.HOUR_OF_DAY) + ":" +
rightNow.get(Calendar.MINUTE) + ".");
You can update editText in each minute using a thread like following
Thread t = new Thread(){
public void run() {
Calendar oldTime = Calendar.getInstance();
oldMinute = oldTime .get(Calendar.MINUTE);
while(true) {
Calendar rightNow= Calendar.getInstance();
newMinute = rightNow.get(Calendar.MINUTE);
if(newMinute != oldMinute) {
oldMinute = newMinute;
mTv.setText("Refreshed! Last updated " +
rightNow.get(Calendar.HOUR) + ":" +
rightNow.get(Calendar.MINUTE) + ".");
}
}
}
t.start();
Well, Calendar.get(Calendar.HOUR) should be returning 12-hour time, but if you wanted to produce your slightly nicer text, you can use the TimeUnit class for parsing simplicity.
long millis = Calendar.getInstance().getTimeInMillis();
String.format("Last updated %d min, %d sec ago.",
TimeUnit.MILLISECONDS.toMinutes(millis),
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
);
i want an alarm to go off when user checks in a checkbox. Here is my code:
if (cb1.isChecked())
{
Calendar calA = Calendar.getInstance();
//calA.set(Calendar.YEAR, Calendar.YEAR);
//calA.set(Calendar.MONTH, Calendar.MONTH);
//calA.set(Calendar.DAY_OF_MONTH, Calendar.DAY_OF_MONTH);
calA.set(Calendar.HOUR_OF_DAY, Calendar.HOUR_OF_DAY);
calA.set(Calendar.MINUTE, Calendar.MINUTE);
calA.set(Calendar.SECOND, Calendar.SECOND);
calA.set(Calendar.MILLISECOND, Calendar.MILLISECOND);
alarmManager.set(AlarmManager.RTC_WAKEUP, calA.getTimeInMillis(), pendingIntentA);
Toast.makeText(main.this, "Set time: " + String.valueOf(calA.getTime()), Toast.LENGTH_SHORT).show();
}
Other codes are working fine, and if i set the hour and minute to specific ones, like
calA.set(Calendar.HOUR_OF_DAY, 15);
calA.set(Calendar.MINUTE, 24);
it's working, but with this code i always get this toast message:
Sat Mar 05 11:12:00 or Sat Mar 05 11:12:13
(neither the date nor the time is good)
What is wrong with my code?
Calendar.HOUR_OF_DAY is a constant, which just so happens to be an integer.
When you
calA.set(Calendar.HOUR_OF_DAY, Calendar.HOUR_OF_DAY);
you are in fact setting the hour of day to whatever number happens to have been chosen for this constant. This value has no real meaning in relation to the hour of day, so it'll produce a garbage result.
When you get the calendar, it's by default set to the current time, so if that's what you're going for, simply don't set the time:
Like other locale-sensitive classes, Calendar provides a class method, getInstance, for getting a generally useful object of this type. Calendar's getInstance method returns a Calendar object whose calendar fields have been initialized with the current date and time:
Calendar rightNow = Calendar.getInstance();
If you then want to set a time like "5 minutes into the future", do something like:
calA.add(Calendar.MINUTE, 5);
If you still get an incorrect time, verify that the system time is set correctly.
Source:
Calendar documentation
Calendar calA = Calendar.getInstance(); returns a calendar object whose locale is based on system settings and whose time fields have been initialized with the current date and time.
Sebastian P is right that Calendar.HOUR_OF_DAY is a constant, a key/index used for referencing the actual hour value.
See http://developer.android.com/reference/java/util/Calendar.html