SimpleDateFormat parsing problem

Hi All,
I am creating a date "12142007 14:30" by parsing this string with the SimpleDateFormat object. However, when I convert it back to string and ask it to spit it out it gives me a completely different date of "Sun Jun 14 14:00:00 CDT 2009".
Am I missing something here ? Not sure if i have to put something in the parse position. Any help would be appreciated.
Thanks and Regards,
*public void test2() throws Exception{*
*          SimpleDateFormat sdf3 = new SimpleDateFormat("MMddyyyy HH:MM");*
*          Date theDate = sdf3.parse("12142007 14:30");*
*          System.out.println(theDate.toString());          *
Edited by: mikematic_wha on Dec 14, 2007 9:42 AM

PeterBro wrote:
Try that again with the spelling corrected
public void Calest()
          String tempDate = textField2.getText(); // ie 20080128
          SimpleDateFormat ofd = new SimpleDateFormat("yyyyMMdd");
     Date tod = odf.parse(tempDate); // this line errors
     }Peter,
Why don't you return to the thread you started where you got a couple of answers and if you have a follow up question post it there.
[http://forum.java.sun.com/thread.jspa?threadID=5290540]

Similar Messages

  • SimpleDateFormat.parse() Problem

    My Code:
    public class Sdf {
        public Sdf() {
             SimpleDateFormat s1 = new SimpleDateFormat("DD:MM:yyyy:HH:mm:ss:a:z");
             try{
             Date myDate = s1.parse("15:11:2006:21:12:13:PM:GMT");
             System.out.println(myDate.toString());
             catch(Exception ex){
                  System.out.println("EX");
        public static void main(String s[]){
             new Sdf();
    }The output: Sun Jan 15 21:12:13 GMT 2006
    My Problem
    The month entered in the parse method is 11 (Nov) but parsing returns January.
    I am doing something wrong obviously, so what do I need to do to fix this?
    My goal is to get a long value from that string pattern.
    Thanks so much, for any help you can give.

    Hmm, when you think about it, the whole operation is extremely complicated anyway. Accounting for leap years, leap seconds daylight saving times, locale specific stuff and of course 'bad' entry�s such as Jan 32nd.
    I spent hours trying to fix that problem. Manually calculating values by multiplying 1000*60*60 for hours, 24 hour time V's 12 hour time was another source of compilcation etc. I pretty much opened a can of worms that I wanted to close quite quickly again.
    Some values I'd imagine would have to take precedence over others to limit the many combinations and permutations. What takes precedence over what is another story but I guess reading the API more carefully would eliminate the need to know such things for most purposes.
    I certainly won't be forgetting the difference between DD and dd again in a hurry.
    Thanks Again.

  • Strange result of SimpleDateFormat.parse()

    Hi,
    I'm having trouble with the parse data function as it does not return the correct hour.
    Here is what I'm doing:
    Date nullDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse("1900-01-01T00:00:00-0000");I would now expect nullDate to be Mon Jan 01 00:00:00 CET 1900
    But instead, it is Mon Jan 01 00:09:21 CET 1900
    Personally I cannot think of a reason why the time is not 0.
    Any ideas?

    I don't see the problem you see. What version of Java on what OS and in what time zone?
    P.S. I would certainly set the time zone for the parser i.e.
           SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
            parser.setTimeZone(TimeZone.getTimeZone("UTC"));
            Date nullDate = parser.parse("1900-01-01T00:00:00-0000");
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
            System.out.println(formatter.format(nullDate));On my Ubuntu 10.04 using JDK 1.6.0_20 in London (currently GMT) time zone I get
    1900-01-01 00:00:00 GMT

  • SimpleDateFormat parsing difficulty

    Hello all,
    Recently, I had to parse Strings into Dates using SimpleDateFormat. The difficulty I had was because the Strings had timezone offsets. The code below shows the 3 tests it took to create a Date object of specified TimeZone.
    Test 1
    Fails because I don't set the TimeZone for SimpleDateFormat.
    Test 2
    Works for the first String because the TimeZone matches the timezone in the String.
    Test 3
    Works for all Strings, but is cumbersome because I have to parse the end of the String myself.
    My question is this: Shouldn't SimpleDateFormat parse a String directly into a Date without having you to specify the TimeZone of that Date? This problem was very annoying to solve and goes against logic (at least mine!).
    I'm interested in any thoughts on this matter. Am I being unreasonable, or is this poorly explained in the API?
    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.SimpleTimeZone;
    public class DateTests {
         private static String DATE_FORMAT = "yyyyMMddHHmmss.SSSZ";
         private static String[] TEST_DATA = {
              "20020125120434.175+0800",
              "20031101195801.942+0000",
              "20041231000159.999-0536",
              "20050220165427.531-1100"
         private static int MINUTE = 60 * 1000; //in milliseconds
         private static int HOUR = 60 * MINUTE;
         public static void main(String[] args) {
              test1();
              test2();
              test3();
         private static void test1() {
              System.out.println("**** TEST 1 ****\n");
              DateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
              formatter.setLenient(false); //want to check that dates are valid
              for (String dateString : TEST_DATA) {
                   try {
                        Date date = formatter.parse(dateString);
                        System.out.println("Success! The date is: "+date.toString());
                   } catch (ParseException e) {
                        System.out.println(dateString + " has error index of: " + e.getErrorOffset());
              //out of curiousity, lets see the String representation of the current date & time
              Date now = new Date();
              String currentDate = formatter.format(now);
              System.out.println("\nThe current date as a String: "+currentDate);
              System.out.println("\n");
         private static void test2() {
              System.out.println("**** TEST 2 ****\n");
              DateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
              formatter.setLenient(false); //want to check that dates are valid
              //lets make the timezone +0800
              formatter.setTimeZone(new SimpleTimeZone(8 * HOUR, "GMT")); //8 hour offset
              for (String dateString : TEST_DATA) {
                   try {
                        Date date = formatter.parse(dateString);
                        System.out.println("Success! The date is: "+date.toString());
                   } catch (ParseException e) {
                        System.out.println(dateString + " has error index of: " + e.getErrorOffset());
              System.out.println("\nSuccess for the first date. Why? The timezone of the formatter matches the date.");
              System.out.println("\n");
         private static void test3() {
              System.out.println("**** TEST 3 ****\n");
              DateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
              formatter.setLenient(false); //want to check that dates are valid
              for (String dateString : TEST_DATA) {
                   try {
                        //lets set a timezone for each individual date
                        int length = dateString.length();
                        int gmtMinutes = Integer.parseInt(dateString.substring(length-2, length));
                        int gmtHours = Integer.parseInt(dateString.substring(length-4, length-2));
                        int timeZone = gmtMinutes * MINUTE + gmtHours * HOUR;
                        timeZone = dateString.charAt(length-5) == '+' ? timeZone : -timeZone;
                        formatter.setTimeZone(new SimpleTimeZone(timeZone, "GMT"));
                        Date date = formatter.parse(dateString);
                        System.out.println("Success! The date is: "+date.toString());
                   } catch (ParseException e) {
                        System.out.println(dateString + " has error index of: " + e.getErrorOffset());
    }-Muel

    Date objects don't have time zones.
    This is true, my problem was that I needed to parse both the Date and the TimeZone from a String. I got misled by the SimpleDateFormat documentation (the symbol Z), and somehow got the impression that a Date should have an associated TimeZone!
    In hindsight, it is clear that Z should be used for Date strings containing a timezone and that SimpleDateFormat uses the timezone to modify the Date so that it's correct for the timezone of the current machine. If that makes sense!
    -Muel

  • WIJ 20002 xml Parser Problem - Rich Client

    Hi,
    I have a problem with the rich client on a new installation:
    Business Objects Enterprise XI 3.1 SP3 on Windows 2008 Standard.
    If I connect with the rich client "import document"is disabled.
    if I try to create a new document from the rich client it returns the error below (I used the rich client on two workstations):
    WIJ 20002
    Version: null
    Analisi dello stack:
    java.lang.RuntimeException: java.lang.RuntimeException: XML parser problem:
    XMLJaxpParser.parse(): Element type "ABOUT_Patentnumbers" must be followed by either attribute specification, ">" or "/>".
    at com.businessobjects.wp.xml.jaxp.XMLJaxpParser.parse (Unknown Source)
    at.com.businessobjects.webi.richclient.XMLviaOccaRC.getServerConfiguration (Unknown Source)
    Have you any solution?

    The fixpack 3.5 client resolves the problem.

  • Report query parsing problem

    I didn't find any report of this problem...
    Using APEX 3.0.1.00.07, I have a report of type "SQL Query (PL/SQL function body returning SQL query)" with the "Use Generic Column Names (parse query at runtime only)" radio button selected.
    When the region source contains the string "ORDER BY" in any form that I've tried (even in a comment), attempting to save the region fails with "Your query can't include an "ORDER BY" clause when having column heading sorting enabled."
    I do indeed have column sorting enabled on certain columns, but I don't see how that is relevant under these circumstances since the query produced at runtime does not have an ORDER BY clause.
    Am I overlooking something or is this a parsing problem?
    Rodney

    Rodney,
    It's just checking for order by being included in your query, and if so and you have column heading sorting enabled, it's raising this error because you can't have both (even if it's commented out).
    Regards,
    Marc

  • SAX parser problem in JDK1.5

    I have parse the xml file using SAX in jdk1.5 environment. During the parsing, it missed the some text content.
    for example
    <employeeid>
    <empid>1001</empid>
    <empid>1002</empid>
    </employeeid>
    If i have parse the above xml file using SAX in jdk1.5 environment. The output is
    1001
    100
    during the parsing , SAX parser misses digit of 2.
    if i have parse the above xml file using SAX in jdk1.4 environment , it is working fine.
    what is the problem in jdk1.5
    please help
    bala

    What I expect the problem to be was discussed recently in a topic titled "SAX Parser Problems" that was started on March 14 at 6:59 AM by JackoBS.
    Read that and see if it fixes your problem. If so, it is not a JDK1.5 problem, but a user error.
    Dave Patterson

  • Parsing Problems? ImageIcon and BufferedImage

    Hi to everyone
    Could I ask if I will to send ImageIcon with BufferedImage as its arguement. Then what should I receieve from the server? ImageIcon only or ImageIcon with BufferedImage as its arugement?
    Any help will be appreciated. Thank You.

    I am sending ImageIcon over to the server, hence the server will receive as ImageIcon.
    However, when I want to pass the ImageIcon which being parse to Image, this step is ok. Lastly when I want to parse the Image to BufferedImage image, I am encountering parsing problems, hence could u advise me further.
    The error message "Receiving failed: java.lang.ClassCastException"
    Any help will be appreciated. Thank You.
         public void getImage()
              //Object input = null;
            Image images = null;
              try{
                   imgIcon = (ImageIcon)oin.readObject();
                   System.out.println("Icon Width: "+imgIcon.getIconWidth());
                   while((images = imgIcon.getImage()) != null)
                        System.out.println("Images Width: "+Image.getWidth(images));
                        BufferedImage bimage = (BufferedImage)images; // PROBLEM LIES HERE
                        System.out.println("Bimage Width: "+bimage.getWidth());
                        ImageServerConnection.writeImage(bimage, "happy.jpg");
                        //String fname = "joalicia";
                        //create an new folder to store those sent images.
                        //File f = new File ("c:\\Sweet", fname);
                        //create(f);
              }catch(Exception e){
                   System.err.println("Receiving failed: "+ e);
         }

  • 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.

  • 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%

  • SimpleDateFormat parse error

    Hy,
    I've an error when parsing a date with the parse function of the SimpleDateFormat class.
    Date birthDate = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmZ");
    try {
         birthDate = sdf.parse("198012160810Z");
    } catch (ParseException e) {
         System.out.println(e.getMessage());
    The exception Unparseable date: "198012160810Z" is raised.
    I've no error if I remove the "Z" at the end of the date. I've checked in the RFC 822, the Z time zone is accepted.
    Does somebody knows the problem ?

    thegillou wrote:
    Thanks for your response everybody. I'ts OK.
    warnerja : I can't respond to say thank you when I sleep.....you know the timezones..........Sure, but I also know you were answered within 6 minutes after you posted the question. So you really are of the type to post a question and immediately go nighty-night rather than see if there will be replies soon? Hard to believe.
    Anyway, you're welcome.

  • SimpleDateFormat parses wrong date successfully (lenient = false). Why?

    Hi
    I've got a problem validating date by SimpleDateFormat. Format "yyyy" successfully parses string like "2009-78" into date 01.01.2009. Can you please help me with it?
    Here is my code:
    SimpleDateFormat format = new SimpleDateFormat("yyyy");
    format.setLenient(false);
    String dateStr = "2009-78";
    Date date;
    try {
        date = format.parse(dateStr);
    } catch (ParseException e) {
        date = null;
        e.printStackTrace();
    System.out.println(String.format("String '%s' parsed to date %s", dateStr, date));Output:
    String '2009-78' parsed to date Thu Jan 01 00:00:00 MSK 2009I need an exception to be thrown in such situation. How can I check where the string represents a correct date?
    Thanks for your help.
    Evgeny
    Edited by: su.eug on Apr 13, 2009 12:56 AM

    Read the comments in the API:
    [http://java.sun.com/javase/6/docs/api/java/text/DateFormat.html#parse(java.lang.String)|http://java.sun.com/javase/6/docs/api/java/text/DateFormat.html#parse(java.lang.String)]
    You could try the other overload of parse, if you want to test whether the whole String was used:
    [http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html#parse(java.lang.String, java.text.ParsePosition)|http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html#parse(java.lang.String,%20java.text.ParsePosition)]
    (Sorry--the second link doesn't go to the right place. There is a version of "parse" with two parameters, which you can use to determine if the whole String was used.)

  • SimpleDateFormat parse fails !!!

    Hi guys, has anyone have a solution to this problem:
      SimpleDateFormat fr = new SimpleDateFormat("dd-MM-yyyy");
        fr.setLenient(false);
        System.out.println(fr.parse("10-10-00"));-SimpleDateFormat seems not capable to parse 00 year when year is in four digit format.
    Is there any trick to parse this as a 2000 year as a simple way ???
    Thanks in advance

    I know if I use 2 digits the problem gets solved, I
    need to solve it because there are customers that
    need four digits in format, so I need to be able to
    parse in 4 digits 2000 year in a faster way
    It sounds like you're failing to distinguish between parsing and formatting. If you need to parse a four-digit year, then feed it a string with a four-digit year. You may need to use more than one DateFormat object; e.g., one for parsing, one for formatting.
    Formatting a Date Using a Custom Format
    Parsing a Date Using a Custom Format

  • SimpleDateFormat: Parse String To Date

    Hi
    I'm trying to parse Date-String to Date. But the Date-String I want to parse is embedded in a Text like:
    Bla bla bla bla bla bla 2004-05-05 bla bla bla bla bla.
    So I tried the attached Class to solve the problem, but it didn't work.
    Any ideas?
    Thanks Bona
    public class Test {
    private static SimpleDateFormat dateFormat = new SimpleDateFormat();
    private String text;
    private Date date;
    public Test() {
    /ry {
    text = "Bla bla bla bla bla bla 2004-05-05 bla bla bla bla bla.";
    date = toDate(text, "yyyy-MM-dd");
    System.out.println("Datum: "+date);
    } catch (ParseException pe) {
    System.out.println(pe.getMessage());
    public static void main(String[] args) {
    Test test1 = new Test();
    public static Date toDate(String dateString, String dateFormatPattern)
    throws ParseException {
    Date date = null;
    dateFormat.applyPattern(dateFormatPattern);
    dateFormat.setLenient(true);
    date = dateFormat.parse(dateString);
    return date;
    }

    Well, you need to extract the date pattern from that String.
    You can use regular expressions to do that. See theRegex package for info on how to do that.
    BTW - AFAIK, lenient date parsing means, that the parser accepts stuff that matches the pattern, but contains illegal values like "2004-02-30" ...

  • XML parsing problem

    Hi, my problem is :
    In my Application i want to parse an XML file with DOM parser. The problem is that in my Project "MyProject -> Project Properties -> Libraries and Classpath"
    I have included some 15 libraries which are useful for my Application: ADF Faces Runtime 11, ADF Web Runtime and etc.
    Problems are causing the libraries: BC4J Runtime,ADF Model Runtime, MDS Runtime Dependencies
    because when added my source which is parsing an XML file stops working.The source code is:
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    File file =
    new File("C:\\Documents and Settings\\ilia\\Desktop\\begin.xml");
    Document doc = db.parse(file);
    Element root = doc.getDocumentElement();
    NodeList dots = root.getElementsByTagName("w:t");
    Element firstDot = (Element)dots.item(0);
    String textValue = firstDot.getFirstChild().getNodeValue();
    I use DOM because i need to change some values in the XML file, but its not working neither for reading nor for writing.When debugging I see that it gets the root of the xml but " firstDot.getFirstChild().getNodeValue() " returns null and it breaks with NullPointerException. And that's only when the libraries mentioned above are added to the project. Without them it works just fine !
    I don't know, it's like when added the parser validates my xml against some schema and returns null.
    The xml file is very simple MS Word Document saved as .xml .But I don't think that's the problem.
    Thanks in advance !
    iliya

    Hi all,
    I found the solution to my problem.The right way to parse and change an XML file with DOM parser using the Oracle XML Parser v2 should look like this:
    JXDocumentBuilderFactory factory =
    (JXDocumentBuilderFactory)JXDocumentBuilderFactory.newInstance();
    JXDocumentBuilder documentBuilder =
    (JXDocumentBuilder)factory.newDocumentBuilder();
    File file = new File("c:/Documents and Settings/ilia/Desktop/begin.xml");
    InputStream input =
    new FileInputStream(file);
    XMLDocument xmlDocument = (XMLDocument)(documentBuilder.parse(input));
    System.out.println("Encoding: " + xmlDocument.getEncoding());
    System.out.println("Version: " + xmlDocument.getVersion());
    NodeList namespaceNodeList =
    xmlDocument.getElementsByTagNameNS("http://schemas.microsoft.com/office/word/2003/wordml","t");
    XMLElement namespaceElement17 = (XMLElement)namespaceNodeList.item(17);
    namespaceElement17.getFirstChild().setNodeValue("someString");

Maybe you are looking for