Results 1 to 4 of 4
  1. #1
    ravl13 is offline Member
    Join Date
    Aug 2011
    Posts
    6
    Rep Power
    0

    Default Manually setting a date using Calendar and Date

    Greetings,

    I'm trying to take a Date called endDate, and create a second Date object called startOfEndYear which holds the first date of of endDate's year. So, if endDate was "Oct 21, 2010", then I'd want startOfEndYear to be "Jan 1, 2010". My code for attempting to do so follows:

    Java Code:
    //Assume that endDate has already been set to "Oct 21, 2010"
    
                    cal.setTime(endDate);
    		int endYear = cal.get(cal.YEAR);
    		System.out.println("end year is " + endYear);
    		DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM);
    	
    		Date startOfEndYear = df.parse("Jan 1, "+ endYear); //This line gets underlined in red in Eclipse
    The explanation of the red underlining says "Unhandled exception type ParseException". How can I correctly code that last line?

    Thanks,
    -ravl13

  2. #2
    SFNYC is offline Member
    Join Date
    Sep 2010
    Posts
    16
    Rep Power
    0

    Default Re: Manually setting a date using Calendar and Date

    Maybe you can try something like this:

    Java Code:
    $ 
          Calendar cal2 = (Calendar) cal.clone();
          cal2.set(Calendar.MONTH, Calendar.JANUARY);
          cal2.set(Calendar.DAY_OF_MONTH, 1);
          Date startOfEndYear = cal2.getTime();

  3. #3
    milovan is offline Senior Member
    Join Date
    Jan 2011
    Location
    Belgrade, Serbia
    Posts
    301
    Rep Power
    4

    Default Re: Manually setting a date using Calendar and Date

    surround that line with try - catch block

  4. #4
    ravl13 is offline Member
    Join Date
    Aug 2011
    Posts
    6
    Rep Power
    0

    Default Re: Manually setting a date using Calendar and Date

    OK, that basically works, thanks. I used similar code to revalue the original "cal" object; I didn't know how to set calendar values.

    (by the way, for anyone just looking, I had already created a Calendar instance called cal in the above code, but I forgot to mention it)

Similar Threads

  1. Calendar object? - Getting date from user
    By hiei_yasha in forum New To Java
    Replies: 9
    Last Post: 01-23-2011, 03:58 AM
  2. Calendar date problem
    By groobelar in forum New To Java
    Replies: 2
    Last Post: 01-17-2010, 03:47 AM
  3. Creating a Gregorian Calendar using a Date object gives date - 1
    By prachi_goliwadekar in forum New To Java
    Replies: 1
    Last Post: 05-08-2008, 08:32 PM
  4. java Date and Calendar
    By valoyivd in forum New To Java
    Replies: 1
    Last Post: 03-30-2008, 06:49 PM
  5. Calendar.DATE
    By mew in forum New To Java
    Replies: 1
    Last Post: 01-04-2008, 07:51 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •