Link to home
Start Free TrialLog in
Avatar of maskedavenger
maskedavenger

asked on

SimpleDateFormat pattern to produce 2002-01-02T09:30:47-05:00

Hi Guys,

I want to format a date such as 2002-01-02T09:30:47-05:00 using the java.text.SimpleDateFormat class.  

The closest I have come to this format is using this pattern:
yyyy-MM-dd'T'HH:mm:ssZ
This results in: 2007-10-12T11:01:26+0200

Carefully note the +0200 part, I need to have a colon between the hours and minutes.  That is +02:00.
My desired result after formatting should then be: 2007-10-12T11:01:26+02:00

How can I modify this pattern?

Thanks M.A
SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of maskedavenger
maskedavenger

ASKER

This was my original solution:

  private static SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
   
  /**
   * Convert date into a formatted string
   */
  public static String formatToString(Date dateToFormat) {
    StringBuffer buffer = new StringBuffer(dateFormatter.format(dateToFormat));
   
    // We have to manually insert a colon
    // i.e 2002-01-02T09:30:47-0500 becomes 2002-01-02T09:30:47-05:00
    buffer.insert(buffer.length() - 2, ':');
   
    return buffer.toString();
  }

I was hoping there was another solution though :)
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>>I was hoping there was another solution though :)

What sort of thing did you have in mind?
You *could* do it in one line if that's the sort of thing you meant...
Well looking at the http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html#timezone javadocs.

I was thinking there's perhaps a way of using the z character in such a way that it produces the desired result.
>>I was thinking there's perhaps a way of using the z character in such a way that it produces the desired result.

No, because unfortunately the zone info is monolithic as opposed to atomic.
I guess in that case it might be feasible to extend the SimpleDateFormat class and implement one's own zoning logic ... even if it means simply adding a colon to a string :)
Yes. You'd get the offset in milliseconds and format as you wish