Parsing Timezones with SimpleDateFormat

String FLASH_DATE_FORMAT = "EEE MMM d HH:mm:ss zZ yyyy";
DateFormat dateParser = new SimpleDateFormat(FLASH_DATE_FORMAT);
Date date = dateParser.parse("Tue May 10 00:00:00 GMT+0000 2005");I get the message "Unparseable date: "Tue May 10 00:00:00 GMT+0000 2005"".
What's wrong?
I don't think it likes the fact that the timezone (GMT) and adjustment (+0000) are immediately next to oneanother, because if I add a space to the pattern and the date, it works fine.

You shouldnt be setting GMT timezones in your format String.
//pseudo code
SimpleDateFormat dateParser = new SimpleDateFormat("format string);
dateParser.setTimeZone("Your timezone id")//pls look at java.util.TimeZone to obtain the correct timezone id);
dateParser.parse("date string");Cheers,
ram.

Similar Messages

  • Parsing Date with SimpleDateFormat

    Hi,
    In my application, i want to parse date which is in String format.
    The format of Date in String is "yyyyMMdd'T'HHmmss.SSS'Z'" (ex:- 20031201T100116.000Z).
    //Happy Case - Input Param "20031201T100116.000Z"
    //Output : 2003-12-01 10:01:16.0 is the expected output ------- works well.
    //Exception case Input param Value "00000000T000000.000Z"
    But the above case breaks as the expected output is "0000-00-00 00:00:00 ". But the output what i get is
    "0002-11-30 00:00:00.0"
    Greatly appreciate your inputs...,
    Here is my code for the above stated case....
    private static void printDateFormat(String str) throws Exception
    String format = "yyyyMMdd'T'HHmmss.SSS'Z'"; //Desired Format
    ParsePosition pos = new ParsePosition(0);
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    Date date = sdf.parse(str, pos);
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    System.out.println("[After Formatting]" + date.toString());
    java.sql.Timestamp ts = new java.sql.Timestamp(cal.getTime().getTime());
    System.out.println(ts.toString());
    Thanks !
    Priya.Jlus
    IIMS-NZ.

    SimpleDateFormat is set to lenient date parsing by default, so it's trying it's best to come up with an actual date for 0000-00-00 (what would you say a 'zero' month should be?). You can prevent this "approximation" by using "setLenient(false)", but then you will get a null Date reference for non-parseable dates like the one you're using.
    The bottom line is that you're going to have to do some validation for the user input and handle exceptional conditions.
    Hope this helps! :o)

  • Parsing TimeZone using simpleDateFormat

    Hi,
    I have a String: "14/03/2007 21:07:07 Europe/London" which i want to convert into java.sql.Date.
    Any ideas whats the simplest approach?
    I have tried using the SimpleDateFormat( "dd/MM/yyyy hh:mm:ss z" ) but then it fails to parse.
    Seems I am missing something simple here :)
    Ta,

    This smells like a bug in the parse method.
    If you have a date + time + valid timezone string, then the method should be able to create a Date - otherwise, how does one get the correct Date?
    Running the program below resulted in this output and unparseable error (changing the timezone to "PST" runs ok.)
    ***timezone dump = sun.util.calendar.ZoneInfo[id="America/Los_Angeles",offset=-28800000,dstSavings=3600000,useDaylight=true,transitions=185,
    lastRule=java.util.SimpleTimeZone[id=America/Los_Angeles,offset=-28800000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,
    startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]]
    ***timezone id = America/Los_Angeles
    ***data to be parsed = 14/03/2007 21:07:07 America/Los_Angeles
    java.text.ParseException: Unparseable date: "14/03/2007 21:07:07 America/Los_Angeles"
    at java.text.DateFormat.parse(DateFormat.java:337)
    at Time.main(Time.java:22)
    The parse method in DataFormat calls an abstract method which is implemented in SimpleDateFormat. That code is convoluted (!), but certainly appears to me to be trying to match against timezone strings like "America/Los_Angeles".
    Other opinions?
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.TimeZone;
    public class Time
        public static void main(String[] args)
            TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
            // The preceeding line is copied from the TimeZone API example code
            System.out.println("***timezone dump = " + tz);
            System.out.println("***timezone id = " + tz.getID());
            String parseMe = "14/03/2007 21:07:07 " + tz.getID();
            System.out.println("***data to be parsed = " + parseMe);
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss zzzz" );
            try
                Date date = sdf.parse(parseMe);
            catch (ParseException ex)
                ex.printStackTrace();
    }

  • Problem with SimpleDateFormat.parse()

    Hello
    I have a problem with the parse-function in SimpleDateFormat.
    When i try to parse the date Fri Jul 15 17:23:41 2005 with this pattern EEE MMM d HH:mm:ss yyyy i get the exception java.text.ParseException: Unparseable date: "Fri Jul 15 17:23:41 2005".
    This is my code:
    SimpleDateFormat df=new SimpleDateFormat("EEE MMM d HH:mm:ss yyyy");
    try {
      df.parse(strDate);
    } catch (ParseException e) {
      e.printStackTrace();
    }Can someone explain me what i did wrong?
    Thanks
    Matthias

    Since your name is "Matthias" it is possible that your locale is one that does not use the English language. If that is the case then your problem is that "Fri" or "Jul" are not correct abbreviations in your language.
    Easiest way to test this idea is to format a date (such as now) using that SimpleDateFormat object and see what the output looks like.

  • Parsing a time field with SimpleDateFormat

    Our users can not key in a military time, they must key in a time with the ampm designation. We allow a for am, p for pm, m for midnight and n for noon. (Don't ask-I guess they don't understand 12:00pm or 12:00am so they specify 12:00m for midnight and 12:00n for noon.)
    I want to use the parse function, with lenient set to false to validate that they keyed a valid date. This works fine when they key a or p behind the date. If they key m or n, it gives an error. I tried using DateFormatSymbols to allow a,p,m or n for the AmPmStrings. This works fine if lenient is set to true. With lenient set to false, it still gives me an invalid date. I guess it is not recognizing my DateFormatSymbol.
    Not sure if I am going about this the wrong way or if there is an easier way to validate the time. I just thought the parse would be a cleaner way then to substring out the hours and minutes, then validate that they are valid numbers.
    Below is the code I was using. Can anyone explain why this won't work?
    DateFormatSymbols symbols = new DateFormatSymbols();
         String[] ampm = new String[4];
         ampm[0] = new String("A");
         ampm[1] = new String("P");
         ampm[2] = new String("M");
         ampm[3] = new String("N");
         symbols.setAmPmStrings(ampm);
         SimpleDateFormat df = new SimpleDateFormat("hhmma", symbols);
    df.setLenient(false);
    try
    parsedTime = df.parse(time.toUpperCase());
    return true;
    catch (ParseException e)
    errorMessages.add("Invalid Date.");
    return false;
    }

    Well, this isn't gonna help you, but-
    I can't say unequivocally(sp) that this is the case, but after a bit of poking about, it appears that the DateFormatSymbols.setAmPmStrings method ignores everything but the first two entries in the string. That is, if you use
    ampm[0] = new String("M");
    ampm[1] = new String("N");
    ampm[2] = new String("A");
    ampm[3] = new String("P");You will be able to parse M's and N's, but not A's and P's.
    Not sure if that helps you, but there you go.
    Lee

  • Problem with SimpleDateFormat

    Hi all,
    I would like to parse a time (00:00:00) in String format into a Date obj. I am using the following code to achieve it. however, the result come out is not what i expect.
       String fromTimeStr = "00:00:00";
       TimeZone sg = TimeZone.getTimeZone("Asia/Singapore");
       System.out.println("Timezone "+sg);
       SimpleDateFormat DF = new SimpleDateFormat("HH:mm:ss");
       DF.setTimeZone(sg);
       Date time = DF.parse(fromTimeStr);
       System.out.println("DAte time"+ time);the output is as followed:
    Timezone sun.util.calendar.ZoneInfo[id="Asia/Singapore",offset=28800000,dstSavings=0,useDaylight=false,transitions=8,lastRule=null]
    DAte timeThu Jan 01 00:30:00 GMT+08:00 1970
    From what i know, the timezone of Singapore is fallen within the GMT+8 zone; thus the result should be Jan 01 00:00:00 GMT+08:00 1970
    My system timezone is "Kuala Lumpur\Singapore GMT+8".
    Could someone enlighten me what there is 30 minutes extra from the output.
    Thanks

    jnaish wrote:
    This is basically what I'm doing:
    package test;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    public class DateFormatError
         private SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
         private Date dateOfBirth;
         public static void main(String[] args)
              DateFormatError x = new DateFormatError();
              x.run();
         public void run()
              String dob = "10/06/1989";
              try
                   dateOfBirth = sdf.parse(dob);
              catch (Exception e)
              sdf.format(dateOfBirth);
              System.out.println(dateOfBirth.toString());
    }Edited by: jnaish on Feb 4, 2009 12:07 PMHey jnaish, thanks for the SSCCE, but your problem is probably already resolved after phdk's post. Just a small side note: never "swallow exceptions". Never ever! To "swallow an exception" is this:
    try {
      // something that may throw an exception
    } catch(AnException e) {
      // do nothing with it: ie, swallow it
    }because whenever something goes wrong, you will not notice it since nothing is even printed to the screen: this makes debugging your code very hard! Always at least print the stack trace:
    try {
      // something that may throw an exception
    } catch(AnException e) {
      e.printStackTrace();
    }so you will see some helpful message on your screen when something goes wrong.
    Good luck!

  • SAX Parser Validation with Schemas (C, C++ and JAVA)

    We are currently using the Oracle XML Parser for C to parse and validate XML data using the SAX parser interface with validation turned on. We currently define our XML with a DTD, but would like to switch to schemas. However, the Oracle XML Parser 9.2.0.3.0 (C) only validates against a DTD, not a schema when using the SAX interface. Are there plans to add schema validation as an option? If so, when would this be available? Also, the same limitation appears to be true for C++ and JAVA. When will any of these provide SAX parsing with schema validation?
    Thanks!
    John

    Will get back to you after checked with development team...

  • Problem parsing XML with schema when extracted from a jar file

    I am having a problem parsing XML with a schema, both of which are extracted from a jar file. I am using using ZipFile to get InputStream objects for the appropriate ZipEntry objects in the jar file. My XML is encrypted so I decrypt it to a temporary file. I am then attempting to parse the temporary file with the schema using DocumentBuilder.parse.
    I get the following exception:
    org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element '<root element name>'
    This was all working OK before I jarred everything (i.e. when I was using standalone files, rather than InputStreams retrieved from a jar).
    I have output the retrieved XML to a file and compared it with my original source and they are identical.
    I am baffled because the nature of the exception suggests that the schema has been read and parsed correctly but the XML file is not parsing against the schema.
    Any suggestions?
    The code is as follows:
      public void open(File input) throws IOException, CSLXMLException {
        InputStream schema = ZipFileHandler.getResourceAsStream("<jar file name>", "<schema resource name>");
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        try {
          factory.setNamespaceAware(true);
          factory.setValidating(true);
          factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
          factory.setAttribute(JAXP_SCHEMA_SOURCE, schema);
          builder = factory.newDocumentBuilder();
          builder.setErrorHandler(new CSLXMLParseHandler());
        } catch (Exception builderException) {
          throw new CSLXMLException("Error setting up SAX: " + builderException.toString());
        Document document = null;
        try {
          document = builder.parse(input);
        } catch (SAXException parseException) {
          throw new CSLXMLException(parseException.toString());
        }

    I was originally using getSystemResource, which worked fine until I jarred the application. The problem appears to be that resources returned from a jar file cannot be used in the same way as resources returned directly from the file system. You have to use the ZipFile class (or its JarFile subclass) to locate the ZipEntry in the jar file and then use ZipFile.getInputStream(ZipEntry) to convert this to an InputStream. I have seen example code where an InputStream is used for the JAXP_SCHEMA_SOURCE attribute but, for some reason, this did not work with the InputStream returned by ZipFile.getInputStream. Like you, I have also seen examples that use a URL but they appear to be URL's that point to a file not URL's that point to an entry in a jar file.
    Maybe there is another way around this but writing to a file works and I set use File.deleteOnExit() to ensure things are tidied afterwards.

  • Has anyone had a opf parse error with container.xml missing, when it is actually present plz ?

    Has anyone had a opf parse error with container.xml missing, when it is actually present plz ?

    Has anyone had a opf parse error with container.xml missing, when it is actually present plz ?

  • XML parser clashes with WL 5.1

    Hello,
    I see that this question has been asked before but I've seen no answer so
    far. We have code that requires an XML parser. We currently us
    jaxp/xerces/xalan. The version we use is more recent than the one
    included in WL5.1.9. Because of this, we are getting NoClassDefFound
    exceptions when deploying our apps. Or sometimes we get "No such method"
    exceptions. Is there a way, short of getting the sources to all our
    packages and changing the package name, to have more recent XMP parser
    coexist with those of WL?
    If not, what are the versions of the third-party jars bundled with WL
    5.1.9? Is that information documented somewhere? We may also try to
    back-port our code so it confirms to whatever version is included in WL.
    Thanks,
    L
    Laurent Duperval <mailto:[email protected]>
    La situation se cornélise à vue d'oeil!
    -Alambic Talon

    I have seen and dealt with this before.
    I had three versions of Xerces in my classpath. I find that I have to put
    the newest jar file in the front of the classpath. I had Xalan.jar and
    Xerces.jar followed by XML4J followed at the end by weblogicaux.jar and my
    application worked well. You can also make use of the WEB-INF/lib directory
    of your application though I didn't get down to that details and solved my
    methodNotFound problem by modifing the main Classpath.
    Hope that helps.
    IH
    "Laurent Duperval" <[email protected]> wrote in message
    news:3b1e30b6$[email protected]..
    Hello,
    I see that this question has been asked before but I've seen no answer so
    far. We have code that requires an XML parser. We currently us
    jaxp/xerces/xalan. The version we use is more recent than the one
    included in WL5.1.9. Because of this, we are getting NoClassDefFound
    exceptions when deploying our apps. Or sometimes we get "No such method"
    exceptions. Is there a way, short of getting the sources to all our
    packages and changing the package name, to have more recent XMP parser
    coexist with those of WL?
    If not, what are the versions of the third-party jars bundled with WL
    5.1.9? Is that information documented somewhere? We may also try to
    back-port our code so it confirms to whatever version is included in WL.
    Thanks,
    L
    Laurent Duperval <mailto:[email protected]>
    La situation se cornélise à vue d'oeil!
    -Alambic Talon

  • Strange problem with SimpleDateFormat.parse method

    I got something strange with this method.
    String pattern = "yyyy/MM/dd";
    String mydate = "2007/00/10";
    SimpleDateFormat formatter = new SimpleDateFormat(pattern);
    Date newdate = formatter.parse(mydate);
    I get "2006/12/10"
    is this correct.

    dongyisu wrote:
    and there no exception get thrown outYes it does. I ran this:
    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    public class DateFormatTest
       public static final String DEFAULT_DATE_FORMAT = "yyyy/MM/dd";
       public static void main(String[] args)
          DateFormat formatter = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
          formatter.setLenient(false);
          for (int i = 0; i < args.length; ++i)
             try
                Date date = formatter.parse(args);
    System.out.println("input: " + args[i] + " date: " + date);
    catch (ParseException e)
    System.err.println(args[i] + " is not a valid date");
    and got this when I input "2007/00/10":
    com.intellij.rt.execution.application.AppMain DateFormatTest 2007/00/10
    2007/00/10 is not a valid date
    Process finished with exit code 0%

  • Help with SimpleDateFormat and time

    Hi,
    I have a strange result when formating a time!
    Time test = new Time(0);
    DateFormat df = new SimpleDateFormat("HH:mm:ss");
    System.out.println("my date: "+ df.format(test));
    Result is 01:00:00
    Why is this not 00:00:00
    Thanks in advance,
    Pieter

    A Date object represents a moment in time, which can have different textual representations. A Date is represented in Java by a number of milliseconds counted from a fixed moment in time: 00:00 UTC on January 1, 1970 AD (using the Gregorian Calendar), which is the same as 01:00 CET. If that is not the time you mean, you should create a date with a different number of milliseconds (or better yet: use the Calendar class to specify the exact date, time and timezone you mean).
    It doesn't matter what timezone the server is set to or what timezone anything is set to, the Date still represents the same moment in time. The only time it matters is when you want to output a Date for a human to read. If you want everyone to just see the same numbers, explicitly set the timezone on your DateFormat to something fixed (I recommend "UTC" over anything else). Just make sure everyone understands which timezone you use.
    Storing the time as seconds will not help - it already stored as (milli)seconds anyway - nor will any other kind of converter: (Simple)DateFormat already has the capabilities to "convert" Strings to and from Date objects (note that using a DateFormat does NOT change the date in any way, it just displays/parses the date in an appropriate format/timezone).

  • ??? Can't Get the Parsed TimeZone (PART 2) ???

    Hi all,
    Sorry about that first post without comments....
    The issue I'm facing is very simple to describe. First, I'm using J2SE 1.4.0_01 on Win 2k.
    I am running the program below in the U.S. Central Time Zone. The date I am parsing is, as you can see, specified in the the U.S. Eastern Time Zone. After the date is parsed, I need a way to determine what time zone the parsed date was specified in.
    I am parsing a date string ("Jul 13, 1997 14:52:16 EDT") using SimpleDateFormat (see below code). Unfortunately, the smart people at Sun decided to make the parse() method return a java.util.Date object instead of a java.util.Calendar object. Why is this bad? Because java.util.Date does not contain time zone information (which is part of the reason it was deprecated in the first place).
    What's more, after parsing the date, the getTimeZone() of the SimpleDateFormat object does not return the time zone from the date that was just parsed, but instead returns the default time zone (i.e., where my JVM is running).
    This just seems so dumb. Am I missing something? Is there a way for me to get at the time zone of the parsed date after the date is parsed? Yes, I know I could read the date string myself and then figure out the time zone and then map the value to the offset from GMT...but you know, the SimpleDateFormat class is ready doing this!
    Sorry for the sarcastic tone -- I'm really getting fed up w/Sun.
    Thanks!
    import java.text.*;
    import java.util.*;
    public class DateTester {
       public static void main(String[] args) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss zzz");
        String s = "Jul 13, 1997 14:52:16 EDT";
        System.out.println("Starting Time Zone: " + sdf.getTimeZone().getDisplayName());
        Date date = sdf.parse(s);
        System.out.println("The parsed date is: " + sdf.format(date));
        System.out.println("Ending Time Zone: " + sdf.getTimeZone().getDisplayName());
       } // main()
    } // DateTester
    Here's the output from running this program in the Central Time Zone:
    Starting Time Zone: Central Standard Time
    The parsed date is: Jul 13, 1997 13:52:16 CDT
    Ending Time Zone: Central Standard Time

    That's a good try but there are two problems:
    First, I can't go around hard-coding the time zone. If I knew the time zone ahead of time (so to speak), I would not have this problem to begin with.
    Secondly, you might think, "Hey, you know the format of the date is "MMM dd, yyyy HH:mm:ss zzz", why not just pluck off the time zone and set it as theh SimpleDateFormat's time zone...like this:"
       SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss zzz");
       String s = "Jul 13, 1997 14:52:16 EDT";
       // Try to pluck off the Time Zone...
       sdf.setTimeZone(TimeZone.getTimeZone(s.substring(1 + s.lastIndexOf(' '))));Well, the problem with this approach is that SimpleDateFormat does not understand "daylight savings" time zones. I don't want to go into too many details but the point is that any daylight-savings time zones (e.g., EDT, CDT, MDT, etc.) will not be recognized as valid time zones and will instead be intrepreted as GMT.
    Thank you again, Sun Microsystems. Fine design -- much better than Microsoft could ever do!

  • URGENT!! date conversion with SimpleDateFormat

    java.text.SimpleDateFormat sdf = new SimpleDateFormat();
    try
    Date date = sdf.parse(elementValue);
    System.out.println(sdf.format(date));
    application.setDecisionDate(date);
    catch (Exception e)
    e.printStackTrace(System.err);
    }

    And you should always specify the following:
    -Results you got - the exact compiler error, exception - with printStackTrace(), or System.out.println() result. With code you must specify the line that the problem occurs on; add a comment to the code example specifying it.
    -What you expected to get.
    -If possible a small code example demonstrating the problem fully.
    All of the above is missing in this post.
    -Still no idea what the problem is.
    -Still no clear idea of what result was expected. For example is it supposed to verify that a user has typed in the correct date or parse a valid date from a data base? In one case you want the exception to occur, in the other you don't.
    -There is a small code example but it is imcomplete because it doesn't specify what the input value is - what date is being used?

  • I just run into an anoying little bug with SimpleDateFormat......

    Try run this code:
    Filename: Foo.java
    import java.util.*;
    import java.text.*;
    public class Foo {
      public static void main(String args[]) {
        DateFormat df = new SimpleDateFormat("dd.MM.yyyy");
        Date date = null;
        try {
          date = df.parse("31.12.2002");
        } catch (Exception e) {
          e.printStackTrace();
        System.out.println("Date initiated: "+date.toString());
        df = new SimpleDateFormat("yyyy-ww");
        System.out.println("Week expected is 2003-01");
        System.out.println("Rendered week : "+df.format(date));
    End of file
    Output from code:
    H:\>java Foo
    Date initiated: Tue Dec 31 00:00:00 CET 2002
    Week expected is 2003-01
    Rendered week : 2002-01
    Anyone know any workaround to get the expected result?
    I am sitting on a DW project that has met this anoying little bug, and I have posted this to the bug parade aswell, but I have no time to wait for a new release of the JDK :) Hope you can help
    My os:
    Windows 2000 SP 2
    My JDK version (cannot use 1.4):
    java version "1.3.1_04"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.3.1_04-b02)
    Java HotSpot(TM) Client VM (build 1.3.1_04-b02, mixed mode)
    Any help is appreciated.

    As Sun says, calculations using Date are ok for computers. but if you need to do things that people want to do with dates, use Calendar/GregorianCalendar. Here's a couple of examples
    import java.util.*;
    import java.text.*;
    public class Calendar2 {
        public static void main(String[] args) {
            Calendar cal = Calendar.getInstance(); // today as Calendar obj;
            cal.add(cal.MONTH, 6);
            // change to Date object for better format control;
            Date sixMonthsFromNow = cal.getTime();
            // create custom format;
            DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
            // apply format and print;
            System.out.println(sdf.format(sixMonthsFromNow));
    import java.util.*;
    public class Calendar1 {
        public static void main(String[] args) {
            Calendar cal = Calendar.getInstance();
            for( int n = 0; n < 7; n++ ) {
                    System.out.println(cal.get(cal.DATE) + "/" + (cal.get(cal.MONTH) + 1) + "/" + cal.get(cal.YEAR));
                    cal.add(cal.DATE, 1);
    }

Maybe you are looking for