SimpleDateFormat Problem

Hi
I ran into a strange error today with SimpleDateFormat .
In the following code:
SimpleDateFormat format =
            new SimpleDateFormat("yyyyMMddHHmmss");
          format.setLenient(false);
          try
               Date date = format.parse("19850414000000");
          catch (ParseException e)
               e.printStackTrace();
          }I receive an exception:
java.text.ParseException: Unparseable date: "19850414000001"
     at java.text.DateFormat.parse(Unknown Source)
     at test.MainClass.main(MainClass.java:101)
Could someone please tell me whats wrong with the date: 19850414000001 ?
Actually after checking some more, all the times between 19850414000000 and 19850414005959 give this error while for example 19850414010000 or 19850413235959 work fine.
Also this only happens for setLenient(false).
What happened on the 14th of april 1985 that the Parser doesn't want to talk about?
Thanks
Aharon

Funny. This occurs with certain timezones only:
package test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
public class Test {
    public static void main(String... args) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        format.setLenient(false);
        for (String timeZoneId : TimeZone.getAvailableIDs()) {
            format.setTimeZone(TimeZone.getTimeZone(timeZoneId));
            try {
                format.parse("19850414000000");
            } catch (ParseException e) {
                System.out.println("Failed on timezone " + timeZoneId);
Failed on timezone Asia/Gaza
Failed on timezone Asia/Jerusalem
Failed on timezone Asia/Tel_Aviv
Failed on timezone IsraelThere's a pattern .. Something Jewish?

Similar Messages

  • Intermitted SimpleDateFormat problems

    Alright, encountered a very strange problem when using SimpleDateFormat to parse a date string. Primarily, I have 2 applications that exchange data over 2 remote sites using flat-files. They have a timestamp as a header along with some other information. The jobs have not been touched, and the code remains exactly the same. However, SimpleDateFormat.parse() throws a variety of exceptions intermittently but they seem to work most of the time. For simplicity, I have only included the code pertaining to the Date Format being used.
    SimpleDateFormat TIMESTAMP = new SimpleDateFormat("yyyyMMddHHmmss");
    TIMESTAMP.setLenient(false);
    TIMESTAMP.parse(someArbritaryTimestamp);I have already checked the actual flat files, and have found that the timestamp format is indeed valid. For example, today morning the timestamp was 20040229065504 and I got a parse exception.
    I have even had crashes such as the following stack trace when the date was formatted correctly.
    For input string: ".551E"
    - java.lang.NumberFormatException.forInputString(Unknown Source)
    - java.lang.FloatingDecimal.readJavaFormatString(Unknown Source)
    - java.lang.Double.parseDouble(Unknown Source)
    - java.text.DigitList.getDouble(Unknown Source)
    - java.text.DecimalFormat.parse(Unknown Source)
    - java.text.SimpleDateFormat.subParse(Unknown Source)
    - java.text.SimpleDateFormat.parse(Unknown Source)
    - java.text.DateFormat.parse(Unknown Source)
    Another crash was
    For input string: ""
    - java.lang.NumberFormatException.forInputString(Unknown Source)
    - java.lang.Long.parseLong(Unknown Source)
    - java.lang.Long.parseLong(Unknown Source)
    - java.text.DigitList.getLong(Unknown Source)
    - java.text.DecimalFormat.parse(Unknown Source)
    - java.text.SimpleDateFormat.subParse(Unknown Source)
    - java.text.SimpleDateFormat.parse(Unknown Source)
    - java.text.DateFormat.parse(Unknown Source)
    And the most interesting one
    multiple points
    - java.lang.FloatingDecimal.readJavaFormatString(Unknown Source)
    - java.lang.Double.parseDouble(Unknown Source)
    - java.text.DigitList.getDouble(Unknown Source)
    - java.text.DecimalFormat.parse(Unknown Source)
    - java.text.SimpleDateFormat.subParse(Unknown Source)
    - java.text.SimpleDateFormat.parse(Unknown Source)
    - java.text.DateFormat.parse(Unknown Source)
    Searched the forums, couldn't find anything that was remotely similar. Couldn't find a bug in Java as well. Any ideas? If not, the only alternative I can see is that the JVM installed on the machine could possible be corrupted

    Hi,
    I recently encountered this issue in my code, and it really through me for a loop since the code hadn't changed in years. I found this forum posting first (many thanks) which pointed me towards the fact that the problem is around thread safety with the SimpleDateFormat class. I still thought it was a bit odd since my code always calls SimpleDateFormat .parse() from the same thread, and the SimpleDateFormat object is private to my class.
    Following up some more I found this Bug ID (4228335) in the Java Bug Parade. It is marked as closed, since it was fixed via another bug, but as far as I can tell the fix was simply to update the API docs to indicate that SimpleDateFormat is not thread safe. However, this bug ID seems to indicate that the thread-safety issue isn't external to users of SimpleDateFormat , but internal to the code path once parse() or format() are called. There are quite a few angry rants posted against this bug, as well as suggestions on how to address it - a few of those suggestions involve modification to the JDK source code.
    I found that my application exhibited these specific characteristics:
    - the SimpleDateFormat is used extenisvely to format a date string coming back over a Socket connection. Occasionally, the call to SimpleDateFormat .parse() threw a NumberFormatException, but it never occurrred consistently. There did seem to be a corelation between the occurences of this exception, and the processor speed of the PC running the application. On a 3.0 gigahertz machine, it was seen more often.
    java.lang.NumberFormatException: For input string: ""
         at java.lang.NumberFormatException.forInputString(Unknown Source)
         at java.lang.Long.parseLong(Unknown Source)
         at java.lang.Long.parseLong(Unknown Source)
         at java.text.DigitList.getLong(Unknown Source)
         at java.text.DecimalFormat.parse(Unknown Source)
         at java.text.SimpleDateFormat.subParse(Unknown Source)
         at java.text.SimpleDateFormat.parse(Unknown Source)
    Workaround
    Basically I subclassed SimpleDateFormat, overrode the parse() and format() methods and synchronized them. In the parse() method, I catch a NumberFormatException, and try the parse() again. If it fails a second time I simply create a new Date and return it. Fortunately the Date variable is not critical for my application.
    This is certainly not a foolproof solution, and I think synchronizing the parse() and fomat() methods are adjusting the timing enough to reduce the occurences of the exception being thrown. Again, in my code the parse() call is only ever made from a single thread.
    Anyway, I just wanted to share my experience, since I know first-hand how frustrating this bug can be.

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

  • Problem parsing SimpleDateFormat date format to database

    I have a page where I am getting parameter values form another page a constucting
    a string from these values which i then want to insert into my SQL database.
    The field i am putting the data into is of type DATETIME and i am using the SimpleDateFormat to format the string.
    Here is my code
    String startTime = request.getParameter("startHour") + ":" + request.getParameter("startMin")+ ":00";
         String endTime = request.getParameter("endHour") + ":" + request.getParameter("endMin") + ":00";
         String startDate = request.getParameter("startDay") + "-" + request.getParameter("startMonth") + "-" + request.getParameter("startYear");
         String endDate = request.getParameter("endDay") + "-" + request.getParameter("endMonth") + "-" + request.getParameter("endYear");
         scheduleData.startTime = startTime;
         scheduleData.endTime = endTime;
         scheduleData.startDate = startDate;
         scheduleData.endDate = endDate;
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         StringBuffer start = new StringBuffer();
         start.append("'"); // start quote (enclose string values in single quote)
         start.append(scheduleData.startDate);  // or compose it from the parameter values
         start.append(" "); // add space between date and time
         start.append(scheduleData.startTime); // or compose it from the parameter values
         start.append("'"); // end quote (enclose string values in single quote)
         StringBuffer end = new StringBuffer();
         end.append("'"); // start quote (enclose string values in single quote)
         end.append(scheduleData.endDate);  // or compose it from the parameter values
         end.append(" "); // add space between date and time
         end.append(scheduleData.endTime); // or compose it from the parameter values
         end.append("'"); // end quote (enclose string values in single quote)
         Date startSQLDate = new Date();
         startSQLDate = sdf.parse(start.toString());
         Date endSQLDate = new Date();
         endSQLDate = sdf.parse(end.toString());
    Driver DriverinsertSchedule   = (Driver)Class.forName(MM_connAdministration_DRIVER).newInstance();
    Connection ConninsertSchedule = DriverManager.getConnection(MM_connAdministration_STRING,
                                                                MM_connAdministration_USERNAME,
                                                                MM_connAdministration_PASSWORD);
    for (int i = 0; i < scheduleData.participants.length; i++) {
        PreparedStatement insertSchedule =
                              ConninsertSchedule.prepareStatement("INSERT INTO Administration.schedule (Assessment_ID, Participant_ID, Schedule_Name, Restrict_Times, Schedule_Starts, Schedule_Stops, Resrict_Attempts, Max_Attempts)  VALUES ( '"
                                                                      + scheduleData.assessmentID + "', '"
                                                                      + scheduleData.participants[i] + "', '"
                                                                      + scheduleData.scheduleName + "', '"
                                                                      + scheduleData.participants[i] + "', '"
                                                                      + scheduleData.scheduleName + "', '"
                                                                      + scheduleData.timeLimit + "', '" + startSQLDate
                                                                      + "', '" + endSQLDate + "', '"
                                                                      + scheduleData.limitAttempts + "', '"
                                                                      + scheduleData.attemptsAllowed + "' ) ");
        insertSchedule.executeUpdate();
    }I am getting this error.
    javax.servlet.ServletException: Unparseable date: "'01-01-2005 09:00:00'"
    org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:825)     org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:758)     org.apache.jsp.administration.schedules.process_005fschedule_jsp._jspService(process_005fschedule_jsp.java:385)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:94)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:324)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    root cause
    java.text.ParseException: Unparseable date: "'01-01-2005 09:00:00'"
    java.text.DateFormat.parse(Unknown Source)     org.apache.jsp.administration.schedules.process_005fschedule_jsp._jspService(process_005fschedule_jsp.java:133)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:94)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:802)     org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:324)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    Can someone please help me as my project deadline is 2morrow and this is a major problem that needs fixing. Can anyone please tell me what i am doing wrong and how to fix the problem.
    Help would be much appreciated
    Thanks

    Can someone please help me as my project deadline ...You can do one of the following.
    1. Figure out the exact format for time that your database takes. In the previous thread you posted there was a suggestion about that exact format.
    2. Use prepared statements and a java.sql.Timestamp which was also suggested to you in the previous thread you posted.
    3. Give up.

  • New problems with simpledateformat

    sorry guys to my previous post i had solved the issue of formatting my date format..
    but i have a new problem now is that when i enter the 13 mnth 2006 simpledateformat auto helped me rectify to jan of 2007.. and i look through the simpledateformat class it does not have any methods to help me check the validity of the date i am inputting.. is there any other class i have to use to check the validity??

    hmm SimpleDateFormat doesn't have a set lenient
    method only calendar has that...Scroll down some more.

  • Problem with SimpleDateFormat (CommandLine vs WebApp)

    Hello Friends,
    I have a strange problem. Not sure what is the mistake from my side. I have simple class that returns formatted date based on TimeZone. It gives me different result if run on command line vs when used in web app. Below is the code & other information.
    import java.util.*;
    import java.text.*;
    public class Test {
         public static String getDateFormatted(String tZone) {
              DateFormat dfm = new SimpleDateFormat("dd-MMMM-yyyy HH:mm:ss z");
              dfm.setTimeZone(TimeZone.getTimeZone(tZone));
              return dfm.format(new Date());     
         public static void main(String ar[]) {
              System.out.println(getDateFormatted(ar[0]));
    Output From Command Prompt
    java Test PST
    06-October-2008 20:37:01 PDT
    Output From webapp running on Weblogic Server Version 10.0
    06-October-2008 23:37:04 GMT-04:00
    Java version from my command prompt
    java version "1.6.0_06"
    Java(TM) SE Runtime Environment (build 1.6.0_06-b02)
    Java HotSpot(TM) Client VM (build 10.0-b22, mixed mode, sharing)
    To confirm if this problem is due to JRockit that is used as default for Weblogic, I changed Java Home in setDomainEnv.cmd to Sun JDK. But still no luck.
    set BEA_JAVA_HOME=C:\bea\jrockit_150_11
    set SUN_JAVA_HOME=C:\bea\jdk150_11
    if "%JAVA_VENDOR%"=="BEA" (
         set JAVA_HOME=%SUN_JAVA_HOME%
    ) else (
         if "%JAVA_VENDOR%"=="Sun" (
              set JAVA_HOME=%SUN_JAVA_HOME%
         ) else (
              set JAVA_VENDOR=Sun
              set JAVA_HOME=C:\bea\jdk150_11
    Thanks & Appreciate any suggestions

    how are you getting the tZone in web application?
    are you taking it from the request?
    in that case the timezone will be according to the settings in the browser.

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

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

  • Is there a problem on the pattern of SimpleDateFormat to parse a String ?

    Hello,
    I tried to parse a String to a Date using a SimpleDateFormat.
    I must be able to have on the pattern something like : "yyyyMMdd_HH00".
    To get a String from a Date with SimpleDateFormat.format(Date date) it works well, but when a try to parse a String into a Date with SimpleDateFormat.parse(String date) I get a : java.text.ParseException: Unparseable date.
    I try it on a JVM 1.4 and 1.5 for the same result.
    An exemple of code :
              String pattern = "yyyyMMdd_HH00";
              SimpleDateFormat currentFormat = new SimpleDateFormat(pattern);
              Date date = currentFormat.parse("20091223_1000");It seems that adding the '00' after 'HH' raise the exception...
    Has the 'HH00' a particular meaning like on Oracle 'HH24' ?
    Is there a way to add number after the 'HH' ?
    Thanks
    Edit :
    Oh yeah, I forgot, I tryied to use the pattern "yyyyMMdd_HH'00'" using '' to escape the 00 without better result...
    Edited by: Jeremy.Antonucci on 23 déc. 2009 15:25

    The context of this pattern :
    To get a file on a http server, I must build an Url String with a filename using the current date.
    I want to be able to change easily the pattern on a file parameters.
    The date must be ending with 00 for the minutes.
    I may have use a pattern with 'HHmm' and suppress the minutes but if it is change on the futur the code will not work...
    As I can't say if in the futur the url will change for the date pattern or not, I decide to use a pattern like "yyyyMMdd_HH00" that works fine for everything else than parsing a string.
    I create a String date based on the current date on UTC using this pattern and keep it to use it to compose an Url String.
    After I need to know how much time I must sleep before the next execution (on each Hour), so I use this date +1 hour to see if the currentDate during this calculation is higher than this date+1... (I'm surely not clear, but it is not the real problem just for curious ^^)
    A dirty solution is to avoid this problem is to catch this case and do substitution on a temporary pattern of the 'HH00' with 'HHmm'. It's really dirty because nothing says that later a 'HH00' mean always 'HHmm' but I have nothing better...
              String pattern2 = pattern;
              if (pattern.matches(".*HH00$")) {
                   pattern2=pattern.substring(0, (pattern.length()-2))+"mm";
              }Where can I do this bug report ?
    Do you see a good solution ?

  • SimpleDateFormat and TimeZone problem

    Hi all, I know there have been a lot of questions
    concerning this topic, but I've looked over a lot
    of messages and I think I've used all ideas provided,
    yet still I can't fix my problem.
    My problem concerns parsing a date from a HTTP
    packet. I use the following code:
    SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss zzz");
    sdf.setTimeZone(TimeZone.getDefault());
    Date date = sdf.parse(packet.substring(exp_pos+9, endline));Most of the time this code works perfectly, however
    from time to time the parse result is 12 hours of.
    Instead of 14h the result is 2h. HTTP dates use a
    24 hour time.
    I'm using the JVM by Blackdown, version 1.3.1 on
    Debian Linux 2.2.18. The timezone is configured
    correctly in my os. I'm in GMT+1.
    I'm not sure if this is a bug or if I have done something
    wrong.
    Any help would be greatly appreciated.
    Peter

    Looks to me that your time format with lower-case "hh" tells it to use the 12-hour, not 24-hour format, and you're not including the am/pm indicator. So it's doing just what you're telling it to do. If you want 24-hour format, use "HH" instead of "hh".

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

  • Java.text.SimpleDateFormat millisecond problem...

    When I run this code:
    java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat();
    formatter.applyLocalizedPattern("yyyy-MM-dd HH:mm:ss.000000");
    java.util.Date date1 = formatter.parse("2001-08-14 13:49:38.000000", new java.text.ParsePosition(0) );
    System.out.println("Date 1 = " + date1);
    formatter.applyLocalizedPattern("yyyy-MM-dd HH:mm:ss.SSS000");
    java.util.Date date2 = formatter.parse("2001-08-14 13:49:38.000000", new java.text.ParsePosition(0) );
    System.out.println("Date 2 = " + date2);
    The output is:
    Date 1 = Tue Aug 14 13:49:38 GMT+01:00 2001
    Date 2 = null
    The only difference is in the localized pattern, date 1 is generated where milliseconds aren't in the localized pattern, date 2 is generated where milliseconds are in the localized pattern.
    Why is date2 null????

    Hi! When you use the second pattern, it appears that "yyyy-MM-dd HH:mm:ss.SSS000" is not an acceptable pattern. However, "yyyy-MM-dd HH:mm:ss.SSS" works. I'd hazard a guess that when you specify milliseconds, only three places are allowed.
    If you used pattern #2 as you had specified originally, a java.text.ParseException is thrown. With the above modification, it works as expected.
    Hope this helps!
    Cheers!

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

  • SimpleDateFormate has problem in ar_EG Locale

    Hi all,
    This code fails when the machine locale is ar_EG(known Java bug [ http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4823811] )
    try{
    SimpleDateFormat st =new SimpleDateFormat();
    st.applyPattern("yyyy-MM-dd-HH.mm.ss");
    st.parse("2002-12-20-12.18.20");
    I am going to use below code as a workaround and I want to make sure it will not fail in any OS with any Locale .Specially OS does not contain Locale_US (Since I use it )
    SimpleDateFormat st =new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss",Locale.US);
    st.parse("2002-12-20-12.18.20");
    Thanks in advance,
    rona

    Hi all,
    This code fails when the machine locale is ar_EG(known
    Java bug [
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4823
    11] )
    try{
    SimpleDateFormat st =new SimpleDateFormat();
    st.applyPattern("yyyy-MM-dd-HH.mm.ss");
    st.parse("2002-12-20-12.18.20");
    I am going to use below code as a workaround and I
    want to make sure it will not fail in any OS with any
    Locale .Specially OS does not contain Locale_US (Since
    I use it )I don't understand this part.
    >
    SimpleDateFormat st =new
    SimpleDateFormat("yyyy-MM-dd-HH.mm.ss",Locale.US);
    st.parse("2002-12-20-12.18.20");
    Thanks in advance,
    ronaThe constructor which takes Locale as its second arg works on Sun JDK + Linux.

  • Problem with threads in my swing application

    Hi,
    I have some problem in running my swing app. Thre problem is related to threads.
    What i am developing, is a gui framework where i can add different pluggable components to the framework.
    The framework is working fine, but when i press the close action then the gui should close down the present component which is active. The close action is of the framework and the component has the responsibility of checking if it's work is saved or not and hence to throw a message for saving the work, therefore, what i have done is that i call the close method for the component in a separate thread and from my main thread i call the join method for the component's thread.But after join the whole gui hangs.
    I think after the join method even the GUI thread , which is started for every gui, also waits for the component's thread to finish but the component thread can't finish because the gui thread is also waiting for the component to finish. This creates a deadlock situation.
    I dont know wht's happening it's purely my guess.
    One more thing. Why i am calling the component through a different thread, is because , if the component's work is not saved by the user then it must throw a message to save the work. If i continue this message throwing in my main thread only then the main thread doesnt wait for user press of the yes no or cancel button for saving the work . It immediately progresses to the next statement.
    Can anybody help me get out of this?
    Regards,
    amazing_java

    For my original bad thread version, I have rewritten it mimicking javax.swing.Timer
    implementation, reducing average CPU usage to 2 - 3%.
    Will you try this:
    import javax.swing.*;
    import java.awt.*;
    import java.text.*;
    import java.util.*;
    public class SamurayClockW{
      JFrame frame;
      Container con;
      ClockTextFieldW ctf;
      public SamurayClockW(){
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        con = frame.getContentPane();
        ctf = new ClockTextFieldW();
        con.add(ctf, BorderLayout.SOUTH);
        frame.setBounds(100, 100, 300, 300);
        frame.setVisible(true);
        ctf.start();
      public static void main(String[] args){
        new SamurayClockW();
    class ClockTextFieldW extends JTextField implements Runnable{
      String clock;
      boolean running;
      public ClockTextFieldW(){
        setEditable(false);
        setHorizontalAlignment(RIGHT);
      public synchronized void start(){
        running = true;
        Thread t = new Thread(this);
        t.start();
      public synchronized void stop(){
        running = false;
      public synchronized void run(){
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        try{
          while (running){
            clock = sdf.format(new Date());
            SwingUtilities.invokeLater(new Runnable(){
              public void run(){
                setText(clock);
            try{
              wait(1000);
            catch (InterruptedException ie){
              ie.printStackTrace();
        catch (ThreadDeath td){
          running = false;
    }

Maybe you are looking for