Calendar object question

Hi,
I have a Calendar object.
Calendar currentDate = Calendar.getInstance();I'm setting the object to:
java.util.GregorianCalendar[time=1049956535186,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Europe/Berlin",offset=3600000,dstSavings=3600000,useDaylight=true,transitions=143,lastRule=java.util.SimpleTimeZone[id=Europe/Berlin,offset=3600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2003,MONTH=3,WEEK_OF_YEAR=15,WEEK_OF_MONTH=2,DAY_OF_MONTH=10,DAY_OF_YEAR=100,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=2,AM_PM=0,HOUR=8,HOUR_OF_DAY=8,MINUTE=35,SECOND=35,MILLISECOND=186,ZONE_OFFSET=3600000,DST_OFFSET=3600000]
I make a clone of this object:
Calendar currentDate2 = (Calendar)currentDate.clone();Then I set the clone to:
currentDate2.set(Calendar.HOUR,12);
currentDate2.set(Calendar.SECOND,0);
currentDate2.set(Calendar.MINUTE,0);
currentDate2.set(Calendar.MILLISECOND,0);I print currentDate2:
System.out.println("currentDate2="+currentDate2);
System.out.println("currentDate2 hour="+ currentDate2.get(Calendar.HOUR));
System.out.println("currentDate2 minute="+currentDate2.get(Calendar.MINUTE));
System.out.println("currentDate2 second="+currentDate2.get(Calendar.SECOND));
System.out.println("currentDate2 millisecond="+currentDate2.get(Calendar.MILLISECOND));I get these results:
currentDate2=
java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Europe/Berlin",offset=3600000,dstSavings=3600000,useDaylight=true,transitions=143,lastRule=java.util.SimpleTimeZone[id=Europe/Berlin,offset=3600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2003,MONTH=3,WEEK_OF_YEAR=15,WEEK_OF_MONTH=2,DAY_OF_MONTH=10,DAY_OF_YEAR=100,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=2,AM_PM=0,HOUR=12,HOUR_OF_DAY=8,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=3600000,DST_OFFSET=3600000]
currentDate2 hour=0
currentDate2 minute=0
currentDate2 second=0
currentDate2 millisecond=0
What am I doing wrong? When I print the whole "currentDate2" I get the right values of hour, minute, second and millisecond. But when I print one at a time I only get zeros. Why?
An other question:
What is the difference if I write:
currentDate2.get(Calendar.SECOND);orcurrentDate2.SECOND;(it doesn't work if I write like this either).
Thanks in advance

by the way: do use GregorianCalendar instead of Calendar:
GregorianCalendar gc = new GregorianCalendar(); Calendar.getInstance() will return you a locale specific calandar, which will be a GregorianCalendar unless you are in Thiland, in which case you will get a sun.util.BuddhistCalendar.... check out the source code...
now back to the actual question.... i believe that your problem is defenately to do with the confusion between the HOUR and the HOUR_OF_DAY like someone else pointed out as well.... HOUR represents a 12 hour clock hour while the HOUR_OF_DAY represents a 24 hour clock hour.... so in the first you would have to cater for the AM_PM field as well....
when displaying the calendar do System.out.println(currentDate.getTime());
to display it in a more understandable format....
hope this helps
omer

Similar Messages

  • Is there a way to add event details using a calendar object vs. those dumb field entry boxes?

    I have switched from PC to Mac over a year and a half ago, and have been plagued with the "dumb" date entry boxes in iCal and now Reminders on the mac. For one, they don't show you the DAY OF WEEK for an event, it assumes you are parked on that day, but of course reality sets in and causes constant date changes for events. Picking a date in the future would be much more helpful if Apple followed some usability norms in iCal. For instance, if you are booking a flight online, those helpful little calendar objects pop up, and further, they are smart about "end dates and times" for events, knowing it can't be earlier than the start date. Apple iCal unfortunately always thinks you are creating an ALL DAY event, and when you change the start time, it creates the end time for the next day. Not very smart. Or is it me that is not very smart for constantly hawking every little data entry field for correctness. Why, oh why dear lord has Apple not given some usability attention to iCal on the mac??? At least match the interface of the iPhone with a nice little slot machine rolling control.
    Is there an add in?
    Is there hope that Apple will ever fix its lagging Mail and iCal apps on the Mac?
    Please advise. Or just offer a kind word of consolation if there is no hope for a better interface.

    In the future, Swing related questions should be posted in the Swing forum.
    The code you posted is of little use since it uses custom classes so we can't see the behaviour of your code.
    In general if you add a component to a Container at run time then you just use
    container.revalidate()
    This will invoke the LayoutManager and repaint the components in the container based on the new layout.

  • Printing Date with Calendar Object

    I am trying to print the current date of a calender object in a mm/dd/yyyy format.
    When I call system.out.println(now.getInstance()); and scroll through the console, it shows DAY_OF_MONTH=29, YEAR=2006, MONTH=6 for July 29, 2006. I realize months are zero based, so month is really 7. My question is, why does:
    System.out.println(now.MONTH + " " + now.DAY_OF_MONTH + " " + now.YEAR);
    print 2 5 1.
    Logic tells me it should print 6 29 2006.
    I have searched previous posts, and couldn't find one that answers my question. How do I take a Calendar object and print its current set date?

    My question is, why does:My question is: why do you care how a Calendar stores its data? If you want to print it, get a Date instance from it and run it through a SimpleDateFormat to get a String representation of the date.
    Don't mix up data and presentation.
    And to answer your question: you don't print the Calendar's date attributes, but the values of some static constants.

  • Calendar object being buggy

    Hi, I'm not new to Java, but this seems like the best place for this question: I have some code dealing with parsing and reading schedules:
           Calendar now = Calendar.getInstance();
              Calendar startDateTime = (Calendar) startTime.clone();
              Calendar stopDateTime = (Calendar) stopTime.clone();
              startDateTime.set(Calendar.YEAR, now.get(Calendar.YEAR));
              startDateTime.set(Calendar.MONTH, now.get(Calendar.MONTH));
              startDateTime.set(Calendar.DATE, now.get(Calendar.DATE));
              stopDateTime.set(Calendar.YEAR, now.get(Calendar.YEAR));
              stopDateTime.set(Calendar.MONTH, now.get(Calendar.MONTH));
              stopDateTime.set(Calendar.DATE, now.get(Calendar.DATE));
              if (scheduleType == 0) //weekly
                   for (int i = 0; i < schedule.length(); i = i + 3)
                        //System.out.println (TIMEFORMAT.format(startDateTime.getTime()));
                        startDateTime.set(Calendar.DAY_OF_WEEK, Integer.parseInt(schedule.substring(i, i + 1)));
                        stopDateTime.setTime(startDateTime.getTime());
                        stopDateTime.add(Calendar.DATE, Integer.parseInt(schedule.substring(i + 1, i + 3)));
                        System.out.println (TIMEFORMAT.format(startDateTime.getTime()) + " " + TIMEFORMAT.format(new Date()) + " " + TIMEFORMAT.format(stopDateTime.getTime()));
    ...My out put is:
    2008-11-24 09:47:00.000 2008-11-10 10:26:14.981 2008-11-27 15:00:00.000
    Which is not what I though I'd get (startDateTime and stopDateTime should be 2008-11-10, 2008-11-13).
    However, if I uncomment the "System.out.println(TIMEFORMAT.format(startDateTime.getTime()));" right after the if statement, my out put becomes:
    2008-11-10 09:47:00.000 2008-11-10 10:27:33.924 2008-11-13 15:00:00.000
    Which is what I want.
    This makes no sense to me, that System.out.println is apparently "changing" something. The closet I can figure is that System.out.println gives more time for something to do something. Shrugs.
    I figure I can bandaid it by setting the startDateTime/stopDateTime to (Calendar) now.clone(), and then setting the specific hour, minute, second to the stopTime/startTime instead, but this is really bugging me.
    Thanks for any help.

    I've been working with java for 4-5 years, and I'm studying CS for my major, so I thought myself at least not new, but I suppose if the experienced say so, then I guess my self-estimation was wrong. Well, this is a good reality check.
    Before anything else though, about what you said about .getTime() ("It is also setting startDateTime to the current time"). I'm under the impression that .getTime() get's the Calendar object's current time as a Date object (which as far as I've used, seems to be true) and also calculates the millisecond value. So if my Calendar is set to "January 2000", when I call .getTime() on it, do I get back a Date object set to "January 2000" (what I set it to) or "November 2008" (today's date)?
    As for the program, I read in a schedule, a start_time, a stop_time (as well as the schedule_id, but that's not important) from a database, and create a schedule object. Then in one method of my Schedule object I check if the current time is in the schedule. I create startDateTime and stopDateTime objects on the fly since if the program runs overnight to the next week, a startDateTime, stopDateTime created at initialization will be wrong.
    Here's a very heavily stripped down recreated version with a main and the test case I was using so you can run this.
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    public class Schedule2
         //date formatter
         private static final SimpleDateFormat TIMEFORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
         String schedule;
         Calendar startTime = Calendar.getInstance();
         public Schedule2(String schedule, Date startTime)
              this.schedule = schedule;
              this.startTime.setTime(startTime);
         public boolean nowInSchedule()
            Calendar now = Calendar.getInstance();
              Calendar startDateTime = (Calendar) startTime.clone(); //set the time values to correct values
              startDateTime.set(Calendar.YEAR, now.get(Calendar.YEAR)); //set the year/month/date values to correct ones
              startDateTime.set(Calendar.MONTH, now.get(Calendar.MONTH));
              startDateTime.set(Calendar.DATE, now.get(Calendar.DATE));
              for (int i = 0; i < schedule.length(); i = i + 3)
                   //System.out.println(TIMEFORMAT.format(startDateTime.getTime()));
                   startDateTime.set(Calendar.DAY_OF_WEEK, Integer.parseInt(schedule.substring(i, i + 1))); //sets current day_of_week to the one in the schedule
                   System.out.println(TIMEFORMAT.format(startDateTime.getTime()));
                   //when I check the startDateTime.getTime(), here is when I get the wrong date (2008-11-24 instead of the 10th)
              return false;
         public static void main(String [] args)
              Calendar a = Calendar.getInstance();
              a.set(1899, 12, 30, 10, 50, 0);
              Schedule2 sked = new Schedule2 ("203", a.getTime());
              System.out.println(sked.nowInSchedule());     
    }So in my test case, I had "203" as the schedule, meaning every Monday until Thursday (first digit is Monday, second two is the number of days the schedule lasts) and the start_time as "30/12/1899 10:50:00 AM".
    I expected to get back "2008-11-10" since this week's Monday falls on the second, but instead I got "2008-11-24".
    I did read the Calendar API, but I suppose I didn't understand it fully. .set() updates the fields, but not the millisecond value. So, maybe .set(Calendar.DAY_OF_WEEK, ...) is not doing what I think it is doing because the millisecond value isn't computed yet, and .set(Calendar.DAY_OF_WEEK, ..) seems more complicated than just setting straight YEAR/MONTH/DATE.
    I'm using Java 1.4.2 BTW.
    Edited by: Yi.Liu on Nov 10, 2008 12:57 PM

  • Calendar object gone!

    We have just applied some hot fixes to an application that runs Crystal reports XI. Now the calendar object no longer appears when running a parameter report based on the date. Any ideas most welcome urgently

    Hi Martyn,
    Please update us whether running the report through the Crystal Report designer show up the calendar object while prompting or not?
       If 'No' then please update us with the following:
    - What is the exact version of Crystal Reports by moving into the Crystal Report Designer->Help->About Crystal Reports.
    - Please search for the 'Prompting' folder (in the drive in which the Business Objects Enterprise is installed) on a machine which display the calendra icon while prompting.
    - Replace the 'Prompting' folder of the non working machine with the working machine after renaming the existing folder to .OLD.
    - Now run the report again and it should show the calendar icon while prompting.
    If 'Yes' then according to your application which is JAVA/.NET based post your question to the SAP Crystal Reports, version for Eclipse or SAP Crystal Reports, version for Visual Studio  forum respectively.
    Thanks!

  • Changing TimeZone for Calendar object doesnt change its time

    Hy, I have a Calendar object with I have set with a Date but I I want from this calendar with the Date set, set other timezone for this calendar and get the corresponding time(always gettting the correct time if is in daylightsavings) but I get the same time.
    Calendar calendario = Calendar.getInstance
    calendario.setTime(new Date());
    System.out.println(calendario.getTime()); *// for example I get the 14:12:25 hours for GMT+01:00*
    calendario.setTimeZone(TimeZone.getTimeZone("GMT+02:00")); *//change time zone using GMT*
    System.out.println(calendario.getTime()); *// I get the same hour: 14:12:25*
    Why? How to do it using GMT format?
    Thanks
    Edited by: user13162080 on 13-sep-2011 14:31
    Edited by: user13162080 on 13-sep-2011 14:48

    user13162080 wrote:
    Ok, thanks. The last question, this changing of timezone and the hour I am getting, is respecting the timezone daylight saving?, I mean if the TimeZone I set is in daylight savings, I will get the correct hour according to this?What DrClap said.
    However, I think you still may be under some misapprehension about time zones:
    1. A Date does NOT have a timezone, even though it stores a date/time value.
    2. Setting a Calendar's timezone does NOT change the time stored in the Calendar. You may even need to run its complete() or computeFields() method to have the timezone change reflected in all its fields (not sure).
    3. As DrClap said, if you are using a DateFormat to display the Calendar, you need to set its* timezone in order to see what you want (for reason 2 above).
    It's amazing to me that after 10 years this API still gives so many problems (and believe me, you're not the only one).
    One thing you might also want to do is have a look at [url http://joda-time.sourceforge.net/]Joda Time. It's been around for a long time now, and so is quite mature; and is fully interchangeable with standard Java date/time classes. In fact, many of its ideas were under consideration for Java Version 7 as JSR-310, but were decided against (still not quite sure why, as in my view the current API is very poor).
    Winston

  • Get() for Calendar Object

    This may sound stupid, but I tried now for 3 hours without success:
    I created a Calendar "object"(textbox with date, button that allows you to select a date from a menu, and a little lable) with NetBeans design to get the users birthday.
    1. How to I get the date(or String) that the users selects(I tried getText(), getValue() and bunch of other stuff) from the calendar "object".(thus, should I do some conversions etc before retrieving the date.)
    I just want to get the date and save it as a String in the database.
    2. I noticed that you can just choose a date with a year from the current year onwards(thus you can't select for ex 1972). How do a change that for ex the last 100 years can be selected.
    Sorry for this common questions, but i am new to jsp.

    Are you using the JSF Calendar component as part of netbeans? The one referenced here?
    That link demonstrates how to set max/min dates.
    Saving a date as a String in a database? Why not actually save it as a sql date/timestamp? Why String?

  • Urgent. Need help in the Calendar Object.

    Hello developers, best regards!
    Well my problem is that i'm facing a fact that i need a calendar object just like that one when u click the time down there in the taskbar, i need to embedd it in my java windows application.
    To be more clear, if u're familiar with the Visual Basic.NET environment, just the kind of calendars that i need is found there, in which it displays a small box which i can select the months, and accordingly i can select the specific date i need.
    Please i need your help so much.
    Thank you in advance.

    [url http://www.google.co.uk/search?hl=en&q=jcalendar&meta=]click

  • Convert a calendar object to a date object

    hi all...i use a calendar to select date and i want to convert the Calendar object returned to a date object ..how could i do that ?? i use the following lines of code but the Date object returned is not correct ..i mean it's not the one i chose from the calendar
    Date selectedDate=new Date();
    selectedDate=(calendar1.getTime());
    Any one could help....thank you

    Show us the code where you set the calendar to your desired value. Calendar1.getTime()
    should return the relevant date.

  • Date change problem in Calendar object

    Hi i have a calendar object for date representation.
    When i need to go ahead a day i use a add method that adds a day to the Calendar object, and if the date is out of range it adjustes proerly to the next montha and proper date in that next month.
    But it fails for 2 instances in a year.
    From May to June and From October to November.
    This i think is happenning because of the Daylight saving times in the May and October.
    I try to go from May to June but it never does on it's own !! Do i have to explicitly check that for those 2 months or there is any other method ?
    How can i get over it ??
    Please help me with this.
    Shailendra

    Hi
    There may be some other reason for it, coz Day light savings starts in last week of March, not in May.
    And day light savings ends in Last week of October
    Suresh

  • Calendar object for the next week day

    I have a calendar object,
    How can I get the calendar object the comes on the next Tuesday or for that matter any week day.
    For example I have the calendar object for today ie. Monday, 7th Aug 2006. How can I get the calendar object for the first saturday after today.

    What you do is calculate how many days ahead it is.
    This would be the target day, less today's day
    reduced to modulo 7. Add 7 to guarantee the %
    operator works correctly e.g.
    cal.add(Calendar.DAY_OF_YEAR,(7 + Calendar.SATURDAY -
    cal.get(DAY_OF_WEEK)) % 7);
    Requires that the numeric values associated with the days of the week are ordered and one apart. Even thought this is the case, the API does not say this is the case so it should not be assumed.

  • Converting String to Calendar Object

    Hi,
    I nedd to Change the below String to Calendar Object.i want to show the records which are older than half an hour.any other idea which will solve my problems?
    Fri Aug 17 01:56:40 GMT+05:30 1906
    Thanks in advance.
    Regards:
    Akash.

    Look at
    java.text.SimpleDataFormat

  • How to calculate number of days between Calendar objects

    Hi,
    I need to calculate the number of days between two Calendar objects. Here is some sample code:
    Calendar now = Calendar.getInstance();
    now.set(Calendar.HOUR_OF_DAY, 0);
    now.set(Calendar.MINUTE, 0);
    now.set(Calendar.SECOND, 0);
    now.set(Calendar.MILLISECOND, 0);
    // get a calendar that represents a day in the past
    Calendar aDayInThePast = getADayInThePast();
    aDayInThePast.set(Calendar.HOUR_OF_DAY, 0);
    aDayInThePast.set(Calendar.MINUTE, 0);
    aDayInThePast.set(Calendar.SECOND, 0);
    aDayInThePast.set(Calendar.MILLISECOND, 0);
    // how can I calculate the number of days ago this was??
    //it would also be useful to get back a negative number if the day is in the future

    My favorite answer so far is reply 15 by Marc__: http://forum.java.sun.com/thread.jspa?threadID=488668&start=15

  • Calendar object issues ... recompute remaining fields after change?

    Hello all. I'm doing date manipulation and arithmetic, but I'm running into a problem.
    I'm taking a date provided by a user and comparing it the current date. However, it's the month-end that I'm interested in.
    I'm already creating GregorianCalendar objects from each one, and doing the set on the DAY_OF_MONTH field to the value from getActualMaximum(DAY_OF_MONTH).
    The problem I'm having is that when dealing two dates from the same month, the two Calendar objects are >NOT< returning as EQUAL. After converting each object to a Date and running compareTo() (Side Bar: Why isn't compareTo() available in the Calendar class?) I'm not getting zero.
    I tried a toString() on the two objects, and I can see that some of the fields are not exact ... the time field is "?", WEEK_OF_YEAR, WEEK_OF_MONTH are different, etc. I can see the protected method complete() in the API, but attempts to execute them (gcCurrDate.complete()) yield compile errors stating the method is not visible.
    So how does one ask the system to fill in the remaining fields?
    Thanks!
    Steve

    According to the API docs for Calendar:
    "set(f, value) changes field f to value. In addition, it sets an internal member variable to indicate that field f has been changed. Although field f is changed immediately, the calendar's milliseconds is not recomputed until the next call to get(), getTime(), or getTimeInMillis() is made."

  • Calendar object without time

    Hi,
    I need to get a calendar object without displaying the time (hh:mm) field. Can smone help me with this??
    Thanks in advance

    Thanks for the replies..but my requirement is a
    calendar object which i need to set in one of the
    existing bean class set methods which takes in only a
    calendar object (I cant modify the method signature).
    I am pasting my code below..
    The situation is : I get data from database as a
    string read from a file which is then converted into
    a format yyyy-MM-dd using a simple date format. This
    returns a date object which i need to convert to
    calendar without showing the time fields. The prb is
    it is showing the GMT diff as default.
    public static Calendar dateString2Calendar(String s)
    throws ParseException {
    static SimpleDateFormat df = new
    SimpleDateFormat("dd-MMM-yy");
    static SimpleDateFormat df1 = new
    SimpleDateFormat("yyyy-MM-dd");
    Calendar cal = Calendar.getInstance();          
    1 = null;
         Date d2 = null;
         String S1 = null;
         d1 = df.parse(s);
         S1 = df1.format(d1);
         d2 = df1.parse(S1);     
         cal.setTime(d2);     
         return cal;          
    Req output : 2004-09-07
    Current output : 2004-09-07+05:30
    00:00 also not allowed in the output :(The Calendar object represents a particular moment in time - it does not have a format and it always has a time portion. Do not use the toString() method to display it - if you use the System.out.println() method to display it, the toString() method is being still being called. Format the display using SimpleDateFormat as suggested.

Maybe you are looking for