I want to get the hour of day in 24hour cycle. I know that date.getHours() is depreciated. But I'm tempted to use it since I cant get the same result out of calendar.hour call.
It seems call calendar.setTime(now) does not pick up the current date value. Anybody knows what's going on here?
much appreciated.
Date d = new Date();
Calendar c = Calendar.getInstance();
c.setTime(d);
System.out.println("hour: "+Math.abs(c.HOUR-24)+", mins: "+Math.abs(c.MINUTE-60)+", d.h: "+d.getHours() +", d.m: "+d.getMinutes());
You're accessing the HOUR and MINUTE static property of Calendar. These are used as a sort of public static enum so that when you call Calendar.get() or Calendar.set() you can refer to a specific field. To get the actual hours contained within the calendar, you should use:
c.get(Calendar.HOUR);
Related
How to subtract one day in XMLGregorianCalendar?
Also while subtracting how to cope up with following problems :
it does not goes to a negative value in case of first day of the month
in case of 1st Jan of a year, where it needs to go back to a previus year
and other similar stuffs.
Please do not suggest to use any other library like Joda-Time. I know they are great, but I need to get this done using XMLGregorianCalendar only.
Thanks
Just convert to a normal GregorianCalendar, do the arithmetic there, then convert back:
GregorianCalendar calendar = xmlCalendar.toGregorianCalendar();
calendar.add(Calendar.DAY_OF_MONTH, -1);
xmlCalendar = datatypeFactory.newXMLGregorianCalendar(calendar);
(This assumes you already have a DatatypeFactory of course. You can always call DatatypeFactory.newInstance() if necessary.)
XMLGregorianCalendar has an add(Duration) method which you could also use for this computation without needing to convert to a GregorianCalendar first. Here's an example:
DatatypeFactory df = DatatypeFactory.newInstance();
XMLGregorianCalendar calendar1 = ...;
XMLGregorianCalendar calendar2 = (XMLGregorianCalendar) calendar1.clone();
calendar2.add(df.newDuration("-P1D"));
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
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.
I want to add a month to a date...
But I want to assign the result to a new variable without changing the original date.
I'd like to do this the standard way, which seems to be using Calendar.add() but that method changes the Calendar object used for calculation.
So I'm wondering what the "proper" thing to do here is - should I use Object.clone() and cast back to Calendar? Instinctively this seems a bit horrible and wrong. Alternatively should I create a new Calendar object from the original one using a syntax like:
Calendar newCalendar = Calendar.getInstance();
newCalendar.setTime(originalCalendar.getTime());
Seems pretty horrible too... surely there must be an easier way - please somebody tell me I'm missing something!
(...but please don't tell me to use Joda Time or Java 8 - I can't due to project constraints.)
Calendar is not a pretty library so you shouldn't expect it to be.
AFAIK, Java 8 will have a new Date/Time library based on JodaTime. ;)
please don't tell me to use Joda Time - I can't due to project constraints
In that case, just learn to enjoy using Calendar and its quirks.
In case it helps anyone or anyone has any comments here's the code I ended up with:
/**
* Get a new date/time by adding the specified number at the specified granularity
* (day/weeks/months etc.) to a date/time.
* #param dateTime
* Date/time to add to
* #param field
* The calendar field representing granularity (day/weeks/months etc.)
* #param amount
* Amount to be added
* #return A new date/time from performing the calculation
*/
public static Calendar add(final Calendar dateTime, final int field, final int amount) {
// Clone the date/time so the original one isn't changed
Calendar newDateTime = Calendar.getInstance();
Date dateTimeAsMillis = dateTime.getTime();
newDateTime.setTime(dateTimeAsMillis);
// Add the specified amount at the specified granularity
newDateTime.add(field, amount);
return newDateTime;
}
What is wrong with
Calendar resultCalendar = originalCalendar.clone(); // Or any other way of creating a copy
resultCalendar.add(...);
?
If you cannot use Joda-Time and restricted to the standard Date/Calendar API then I would suggest the following:
Calendar calendar = Calendar.getInstance();
Date originalDate = calendar.getTime();
calendar.add(Calendar.MONTH, 1);
Date newDate = calendar.getTime();
calendar.setTime(originalDate);
This will back up you current date, then use calendar to calculate current date + 1 month, and then restore the original settings to the calendar.
If u really don't want to clone a new calendar object, U might retrieve how many days in the current month and then calculate how much time need to span to the next month.
At this time u can just setTime(currentCalendar.getTime() + spanTime);
Currently I have a timestamp for example say, 2012-06-23 14:24:07.975 and
two times - 8AM and 3PM.
In java, how can I check whether the above timestamp is between the particular two time.
In other words, I need to check whether the time in timestamp (2012-06-23 14:24:07.975) falls between 8AM and 3PM or not.
Any suggestions.
You can convert the timestamp into an actual Date afterwards you convert it into a Calendar from where you can extract the hour and check it against your given hours.
Use SimpleDateFormat for getting a Date out of your Timestamp, if you cannot directly convert it.. Afterwards
Calendar cal = new GregorianCalendar();
cal.setTime(yourDate);
int hour = cal.get(Calendar.HOUR_OF_DAY);
Now do your hour check.
before and after methods should help you to do that. See docs.
I suggest using compareTo method in Date.