Java.util.Calendar calculates wrong date when any duration is added

Hi friends,
I am trying to calculate the date through java.util.Calendar object and getting wrong value. Let me explain the scenario -
Scenario1:
I have taken start date and added some duration to that and expecting a new date which should be calculated as (start date+ duration). The value is as below -
start date = 2012-01-09 (9 January 2012 )
duration = 1year, 1month, 20 days
new date = 2013-02-28 ( 28 February 2013)
*Here new date I am expecting is 2013-03-01 (1 March 2013).
Scenario2:
I have taken another set of values as below -
start date = 2011-02-15 (15 February 2011)
duration = 1year, 1month, 15days
new date = 2012-03-30 (30 March 2012)
*Here new date is as expected.
Scenario1 data is giving me wrong result. Please let me know if any more information is required. Any help will be appriciated. Thanks in advance.
Edited by: user560316 on ९ जनवरी, २०१२ ६:२३ अपराह्न
Edited by: user560316 on ९ जनवरी, २०१२ ६:२४ अपराह्न

It all looks pretty straightforward to me. Try running the following code:
public class TestCalendar {
    public static void main(String[] args) {
        java.util.Calendar myDate = java.util.Calendar.getInstance();
        java.text.DateFormat df = new java.text.SimpleDateFormat("dd MMMM yyyy");
        myDate.set(2012, java.util.Calendar.JANUARY, 9);
        System.out.println("Start date = " + df.format(myDate.getTime()));
        myDate.add(java.util.Calendar.YEAR, 1);
        myDate.add(java.util.Calendar.MONTH, 1);
        myDate.add(java.util.Calendar.DAY_OF_MONTH, 20);
        System.out.println("End date = " + df.format(myDate.getTime()));
}This gives the following result:
Start date = 09 January 2012
End date = 01 March 2013

Similar Messages

  • Java.util.Calendar returning wrong Date object

    Example: This was my scenario last night. A server in California has date/time of 'Mon Aug 18'. Current time in Indiana is 'Sun Aug 17'. I use Calendar.getInstance(TimeZone.getTimeZone("America/Indiana/Indianapolis")) to return a Calendar instance. I then call the getTime() method on that instance. It should return a Date object relating to that particular time zone. It will not. It defaults back to the server time. When I print out the Calendar instance everything is good, correct date, correct time,etc. WHY WON'T THE getTime() return the correct java.util.Date???
    Following is the output was run today so the dates happened to be the same so focus on the Time. Output includes Server time, new Calendar values, and the Date returned by calendar instance getTime(). See that the Calendar is getting the correct Time.
    SERVER DATE=Mon Aug 18 15:52:13 CEST 2003
    CALENDAR INSTANCE=java.util.GregorianCalendar[time=1061214732975,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/Indiana/Indianapolis",offset=-18000000,dstSavings=0,useDaylight=false,transitions=35,lastRule=null],firstDayOfWeek=2,minimalDaysInFirstWeek=1,ERA=1,YEAR=2003,MONTH=7,WEEK_OF_YEAR=34,WEEK_OF_MONTH=4,DAY_OF_MONTH=18,DAY_OF_YEAR=230,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=3,AM_PM=0,HOUR=8,HOUR_OF_DAY=8,MINUTE=52,SECOND=12,MILLISECOND=975,ZONE_OFFSET=-18000000,DST_OFFSET=0]
    Date from getTime()=Mon Aug 18 15:52:12 CEST 2003

    I got it worked with using DateFormat.parse !
    The trick is to instantiate a new Date object as a result
    of parsing out of 'localized' date string.
    with below code :
    Calendar localCal = new GregorianCalendar(TimeZone.getTimeZone("America/Los_Angeles"));
    localCal.set(Calendar.DATE, 25);
    localCal.set(Calendar.MONTH, 7);
    localCal.set(Calendar.YEAR, 2003);
    localCal.set(Calendar.HOUR_OF_DAY,6);
    localCal.set(Calendar.MINUTE, 38);
    localCal.set(Calendar.SECOND, 11);
    Calendar sinCal = new GregorianCalendar(TimeZone.getTimeZone("Asia/Singapore"));
    sinCal.setTimeInMillis(localCal.getTimeInMillis());
    int date = sinCal.get(Calendar.DATE);
    int month = sinCal.get(Calendar.MONTH);
    int year = sinCal.get(Calendar.YEAR);
    int hour = sinCal.get(Calendar.HOUR_OF_DAY);
    int min = sinCal.get(Calendar.MINUTE);
    int sec = sinCal.get(Calendar.SECOND);
    String sinTimeString = date + "/" + month + "/" + year + " " + hour + ":" + min + ":" + sec;
    System.out.println("VIDSUtil.hostToLocalTime : time string now in SIN time : " + sinTimeString);
    java.util.Date sinTime = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").parse(sinTimeString);
    System.out.println("time in SIN using Date.toString(): " + sinTime.toString());
    It prints out :
    VIDSUtil.hostToLocalTime : time string now in SIN time : 25/7/2003 21:38:11
    time in SIN using Date.toString(): Fri Jul 25 21:38:11 PDT 2003
    (Ignore the PDT, because Date.toString() defaults where the JVM is running)

  • Why not Deprecate java.util.Date and java.util.Calendar

    With the introduction of java.time, why did you not flag java.util.Date and java.util.Calendar. These classes have been a bane to every Java developer and should never be used again with the introduction of Java 1.8.

    Adding the @Deprecated annotation would only just provide a warning about an old API and recommendation to the developer(s) to no longer use it. Doing so would not break any existing library out there; in fact quite a number of constructors and methods on the Date class have already been flagged deprecated.
    The new java.time package is far superior to Date/Calendar.

  • Java.sql.Date vs java.util.Date vs. java.util.Calendar

    All I want to do is create a java.sql.Date subclass which has the Date(String) constructor, some checks for values and a few other additional methods and that avoids deprecation warnings/errors.
    I am trying to write a wrapper for the java.sql.Date class that would allow a user to create a Date object using the methods:
    Date date1 = new Date(2003, 10, 7);ORDate date2 = new Date("2003-10-07");I am creating classes that mimic MySQL (and eventually other databases) column types in order to allow for data checking since MySQL does not force checks or throw errors as, say, Oracle can be set up to do. All the types EXCEPT the Date, Datetime, Timestamp and Time types for MySQL map nicely to and from java.sql.* objects through wrappers of one sort or another.
    Unfortunately, java.sql.Date, java.sql.Timestamp, java.sql.Time are not so friendly and very confusing.
    One of my problems is that new java.sql.Date(int,int,int); and new java.util.Date(int,int,int); are both deprecated, so if I use them, I get deprecation warnings (errors) on compile.
    Example:
    public class Date extends java.sql.Date implements RangedColumn {
      public static final String RANGE = "FROM '1000-01-01' to '8099-12-31'";
      public static final String TYPE = "DATE";
       * Minimum date allowed by <strong>MySQL</strong>. NOTE: This is a MySQL
       * limitation. Java allows dates from '0000-01-01' while MySQL only supports
       * dates from '1000-01-01'.
      public static final Date MIN_DATE = new Date(1000 + 1900,1,1);
       * Maximum date allowed by <strong>Java</strong>. NOTE: This is a Java limitation, not a MySQL
       * limitation. MySQL allows dates up to '9999-12-31' while Java only supports
       * dates to '8099-12-31'.
      public static final Date MAX_DATE = new Date(8099 + 1900,12,31);
      protected int _precision = 0;
      private java.sql.Date _date = null;
      public Date(int year, int month, int date) {
        // Deprecated, so I get deprecation warnings from the next line:
        super(year,month,date);
        if(! isWithinRange(this))
          throw new ValueOutOfRangeException((RangedColumn)this, "" + this);
      public Date(String s) {
        super(0l);
        // Start Cut-and-paste from java.sql.Date.valueOf(String s)
        int year;
        int month;
        int day;
        int firstDash;
        int secondDash;
        if (s == null) throw new java.lang.IllegalArgumentException();
        firstDash = s.indexOf('-');
        secondDash = s.indexOf('-', firstDash+1);
        if ((firstDash > 0) & (secondDash > 0) & (secondDash < s.length()-1)) {
          year = Integer.parseInt(s.substring(0, firstDash)) - 1900;
          month = Integer.parseInt(s.substring(firstDash+1, secondDash)) - 1;
          day = Integer.parseInt(s.substring(secondDash+1));
        } else {
          throw new java.lang.IllegalArgumentException();
        // End Cut-and-paste from java.sql.Date.valueOf(String s)
        // Next three lines are deprecated, causing warnings.
        this.setYear(year);
        this.setMonth(month);
        this.setDate(day);
        if(! isWithinRange(this))
          throw new ValueOutOfRangeException((RangedColumn)this, "" + this);
      public static boolean isWithinRange(Date date) {
        if(date.before(MIN_DATE))
          return false;
        if(date.after(MAX_DATE))
          return false;
        return true;
      public String getRange() { return RANGE; }
      public int getPrecision() { return _precision; }
      public String getType() { return TYPE; }
    }This works well, but it's deprecated. I don't see how I can use a java.util.Calendar object in stead without either essentially re-writing java.sql.Date almost entirely or losing the ability to be able to use java.sql.PreparedStatement.get[set]Date(int pos, java.sql.Date date);
    So at this point, I am at a loss.
    The deprecation documentation for constructor new Date(int,int,int)says "instead use the constructor Date(long date)", which I can't do unless I do a bunch of expensive String -> [Calendar/Date] -> Milliseconds conversions, and then I can't use "super()", so I'm back to re-writing the class again.
    I can't use setters like java.sql.Date.setYear(int) or java.util.setMonth(int) because they are deprecated too: "replaced by Calendar.set(Calendar.DAY_OF_MONTH, int date)". Well GREAT, I can't go from a Date object to a Calendar object, so how am I supposed to use the "Calendar.set(...)" method!?!? From where I'm sitting, this whole Date deprecation thing seems like a step backward not forward, especially in the java.sql.* realm.
    To prove my point, the non-deprecated method java.sql.Date.valueOf(String) USES the DEPRECATED constructor java.util.Date(int,int,int).
    So, how do I create a java.sql.Date subclass which has the Date(String) constructor that avoids deprecation warnings/errors?
    That's all I really want.
    HELP!

    I appreciate your help, but what I was hoping to accomplish was to have two constructors for my java.sql.Date subclass, one that took (int,int,int) and one that took ("yyyy-MM-dd"). From what I gather from your answers, you don't think it's possible. I would have to have a static instantiator method like:public static java.sql.Date createDate (int year, int month, int date) { ... } OR public static java.sql.Date createDate (String dateString) { ... }Is that correct?
    If it is, I have to go back to the drawing board since it breaks my constructor paradigm for all of my 20 or so other MySQL column objects and, well, that's not acceptable, so I might just keep my deprecations for now.
    -G

  • Web Service Model transforms dateTime elements to java.util.Calendar

    The issue is that my EJB returns a java.util.Date object, the WS that exposes this EJB states in the wsdl that it returns a dateTime element (see attachment). Web Dynpro web-service model, when given the wsdl generates proxies that receive a java.util.Calendar. Later this Calendar object can’t be bound to UI elements (e.g. tables) see error below.
    Has anybody encountered this problem in the past? Do you have a solution, besides manually transferring the java.util.Calendar objects to java.util.Date object?

    Hi Valery,
    I tried changing my return type in a method in the EJB from java.util.Date to java.sql.Date, the problem that I ran into is that I was not able to expose that method in the web service afterwards. This is a bit strange since java.sql.Date is suppose to be supported as a web service Endpoint. I checked this twice just to make sure.

  • Ktoolbar does not recognize "java.util.Calendar"

    Hi!
    Although http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXRPC4.html says that java.util.Calendar is supported, ktoolbar errors out with
    error: Found unknown simple type: java.util.Calendar
    What's wrong? WSDL not compatible with Java ME?
    any help/hint is very much appreciated,
    regards Florian

    To be honest, I am a bit lost.
    I am beginning / trying to develop a mobile app using WTK / Java ME which uses a web service; the WSDL is here: http://www.pegel-mainz.de/WSDL/v3.0/iLON100.WSDL
    Running ktoolbar's stub generator with a local copy of this file, I get the error above, but with a simple MIDlet which just says "Hi", everything builds and runs fine.
    Funny thing, at least for me - or make that "irritating":
    There is no "Stub" in the generated files. The one class which at least extends "java.rmi.Remote" is "MainSoapPort", but that is only an interface.
    But in all tutorials/docs so far I find these Stub-classes to instantiate the service!
    I guess I am doing something fundamentally wrong.
    Any advice/hint/help/link?
    It's very much appreciated (as I'm lost atm)
    regards,
    Florian

  • Convert java.sql.Timestamp to java.util.Calendar?

    What's the best way to convert java.sql.Timestamp to java.util.Calendar?

    Use Calendar's setTime(Date date) method.
    java.sql.Timestamp extends java.util.Date.
    -Roy

  • How to map javax.xml.datatype.XMLGregorianCalendar to java.util.Calendar

    Hi ,
    How to map javax.xml.datatype.XMLGregorianCalendar to java.util.Calendar so that i can use pass String parameter in YYYY-MM-DD format to my Web service.
    I generated the schema classes using Jaxb 2.1.5.
    Please give suggestion
    Thanks in Advance.

    toGregorianCalendar().getTime()

  • Java.util.Calendar

    Where can i find examples for java.util.Calendar
    can someone please tell me ^^
    Thanks a lot

    take a look at
    java.util.GregorianCalendar
    maybe its this you need ...

  • I have a 5s which has been working fine until about a week ago when any calender event added to my phone will not sync with my enterprise server. Any calender event entered on my PC (enterprise) does show on my phone. Mail is working fine both ways,ideas?

    i have a 5s which has been working fine until about a week ago when any calender event added to my phone will not sync with my enterprise server. Any calender event entered on my PC (enterprise) does show on my phone. Mail is working fine both ways,ideas?Iphne 5s and enterprise

    See my reply to this message:
    https://discussions.apple.com/thread/2557520?start=15&tstart=0
    The problem is that the POP3 client is not issuing a DELE command to remove the email from the server.

  • PJC Calendar setDate Wrong date format. Date change failed?

    Forms 10.1.2 using forms demos pjc code.
    The calendar pjc I added to my form works except I can't initialize it with a date. If I try to initialize a date it always produces 'Wrong date format. Date change failed.' error.
    In a post-query trigger, I initialize the calendar's date using:
    SET_CUSTOM_PROPERTY('PJC.CALENDAR',1,'setDate',to_char(:lead.date_received,'DD.MM.YYYY'));
    In the java console, this yields:
    Warning: Wrong date format. Date change failed.
    Warning: Wrong date format. Date change failed.
    I get the same result when using a hardcoded date like:
    SET_CUSTOM_PROPERTY('PJC.CALENDAR',1,'setDate','01.12.2006');
    What is the flaw in my incantation?

    Hello,
    This is the syntax used in the calendarpjc Forms demo:
        call the setDate method on the calendar PJC via the PL/SQL built in
        set_custom_item_property
        convert Oracle date to String recognised by Java
      procedure setDate(d in date) is
      begin
        set_custom_property(lGlobals.hCalendar,1,'setDate',to_char(d,'Mon DD, YYYY'));
      end;     Francois

  • Report returns wrong data when run on server

    Hi,
    I'm runing CRS XI R2 on Windows Server 2003 SP2.  When I refresh a report in the Crystal Reports XI Designer, I'm getting correct data.  But when I schedule the report to run on the server it returns wrong data.  The data is different from what I see when I refresh it from the designer.  In the report I have running totals set up to count customers that meet a certain criteria.  The report is very large.  It take almost 2 hours to refresh.
    I was wondering what is causing the difference in running total data between refreshing it on the designer and running it on the server.  Is it returning wrong data b/c of it not reading all the records?  Should I be making any changes to the server settings?  I saw that under pageserver, there are options for  setting the 'Minutes Before an Idle Report Job is Closed' and 'Database Records To Read When Previewing Or Refreshing a Report".  Do either of those have anything to do with the report returning incorrect data when being scheduled to run on the server?
    Thanks,
    Kim

    Hi Xuandao,
    You would need to Use Cell Binding and Trigger concept to accomplish this.
    Its simple, however, you would have to work on a trial and error basis to understand this concept as implementing the same is subject to your dashboard and WEBI Design.
    Open you LiveOffice.
    Insert your WEBI, Now, go to Object Properties of your WEBI, select the second tab that says Prompt, Here, it lists the prompts that you have for your WEBI. This would also enlist your BEx variables as well. Select this BEx variable and click on the button that says Prompt at the bottom of this window. Here, select choose Excel Data Range and click on the cell select button on the right (small button that lets you choose what cell you want to bind this prompt to), Now select a free cell that would not be even populated later on when you run the dashboard say A1 (remember the value that you select). Click on OK and again OK. The WEBI Refreshes and you can see all the prompt values at the cell A1. These are all the possible values stored for your BEx prompt variables (these values are fetched from BW system dynamically).
    Now, save this LiveOffice, Go to you dashboard. Connect your dashboard to your Live office. Go to Data-> connections-> Now, select the WEBI and in the right hand pane  go to Usage tab, here, Click on Trigger cell button on the right hand side and select A1 in you LiveOffice.
    It should work fine.
    Let me know.
    Rgds,
    Sreekul Nair

  • Date Picker Calendar Show Wrong Date Information Dec/Jan 2014-2015

    When using a Date Picker, the offered Date for January 1st 2015 is a Friday!  It supposed to be a Thursday!
    You can move to February, and return to January again, and it will correct itself.  
    This happens in Office 2007 and 2010
    What's gone wrong?
    IT will also offer the wrong December dates.
    Is there a fix please?

    Re:  Bad date
    Some remote possibilities...
      Your computer's clock has an incorrect date
      The wrong year is entered somewhere as the first day in 2016 is a friday.
      You have the wrong date system selected 1900 vs. 1904 or vice versa.
      You have a 3rd party (non MS) Date Picker that is programmed incorrectly.
      You have Office 2013 (nothing seems to work there)
    There are alternatives and I offer one for Excel...
    a free excel add-in date picker ("Get Your Own Date")
    (no ads, no trackers, no cookies, no registration)
    https://jumpshare.com/b/O5FC6LaBQ6U3UPXjOmX2
    Jim Cone
    Portland, Oregon USA

  • Photos on my Mac show the wrong date when imported from a portable Hard Drive

    I’ve got loads of photos that I had imported from my old PC.Last night I decided to start going through them and trying to get them sorted  
    prior to importing into iphoto. I discovered that some of the pictures (in particular ones I have taken from my old Iphone) all had the same date and time
    assigned to them. When I checked the Exif details, it listed the correct camera etc, but the date created seems to have changed to the date I copied them to my portable hard drive.  
    I thought this was strange as when they were on my PC I thought they were correct. I booted my PC up and checked the portable hard drive on Windows. When viewed on my PC the pictures all have the correct time and date assigned to them. However when I plug the same portable hard drive into my Mac the same files show up as being created on a more recent date (say 20th Jan 2013).
    I’ve done a lot of research last night, although I can find no forum with this exact problem, I feel it must have something to do with compatibility. The portable hard drive is FAT32, and I am assuming that in order to ensure all of the photos information is transferred correctly in needs to be NTFS.
    The problem I have is how do I transfer my files again from my PC to an NTFS drive, whilst keeping all of the correct date and time information assigned to the photos. My understanding is that the 2 aren’t compatible.
    Has anyone ever had this problem? It mainly seems to be with photos I have extracted from my Iphone or edited in some form by rotating them.
    I have a 13" Macbook Pro Retina with OSX Mavericks installed.

    What you may want to do is archive as a Zipfile the photos and then transfer them to the Mac.     It is possible some of the metadata is being lost on the FAT32 formatting.    USB Flashdrive might work better than a FAT32 formatted hard drive, as I do know that most USB Flashdrives are formatted about the same as SD media cards, which manage to preserve the data when copied from camera to Mac.    My big question is, do you still have the photos on media cards?  You might just want to get a media card reader on your Mac, if the photos are not on SD cards, and transfer them over with the media card reader.
    I do believe Retina MacBook Pros all have SD card readers built-in.
    Note: I've asked this be moved to the MacBook Pro forum.  MacBook without the secondary name refers to the consumer notebook Apple stopped making in 2011.

  • How to get event when any library object added to indesign doc?

    I want to do some operation when any library object is added to doc. So please tell me how to get event when any library object is added to the doc. better provide some code snippet.

    Daves61,
    I need to clarify what kind of event you're interested in.
    1. When you click once on page/spead widget in the Pages panel and only widget becomes selected. The layout window remains unchanged. OR
    2. When you doubleclick on page/spread widget the selected master spread appears in the layout window.
    In the first case you work with Pages panel.
    Have a look to file PageTransitionsPanelObserver.cpp from SDK. 
    PageTransitionsPanelObserver::LazyUpdate()
    In the second case you work with Layout window.

Maybe you are looking for