SimpleDateFormat

I have a quick question about SimpleDateFormat. Here's a bit of code:
Calendar cal = Calendar.getInstance();
java.util.Date date = cal.getTime();
String myDate = DateFormat.getDateInstance().format(date);
SimpleDateFormat goformat = new SimpleDateFormat("MMM d, yyyy");
// I am catching this Exception, but left it off here
java.util.Date Date1 = goformat.parse(myDate);
System.out.println(myDate);
System.out.println(Date1);This is the output I am getting:
Jun 21, 2005 // I have the date on my computer in this format
Tue Jun 21 00:00:00 CDT 2005
Why isn't Date1 the same? Should I change myDate into numbers, i.e. 6/21/2005, and then parse it?
Thanks

They are the same. You specified a certain formatting for the String in your SimpleDateFormat initializer. Then, you printed that exact formatting. Date.toString() has its own formatting. You can verify this by trying:
static final public void main(final String[] args) {
        try {
             Date date = new Date();
             Calendar calendar = Calendar.getInstance();
             calendar.setTime(date);
             SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd kk:mm:ss zzz yyyy");
             System.out.println(formatter.format(date));
             System.out.println(date.toString());
         catch (Throwable e) {     
             e.printStackTrace();
    }- Saish

Similar Messages

  • Format SimpleDateFormat

    Hi,all
    I have a problem with formatting date with SimpleDateFormat.
    I need that the date will be of format dd/mm/yyyy hh:mm:ss
    With date all is showing fine,I use dd/MM/yyyy ,but if I add
    hh:mm:ss  instead of right time I give 12:00:00.
    What may be the problem?
    Regards,
    Michael
    Message was edited by:
            Michael Beilin

    Hi Michael,
    See this code to dipplay the date input field value.
    Put the format you need.
    Package
    import java.sql.Date;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    Code:-
    SimpleDateFormat smpdtFormat =new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    String validFr="";
    validFr = wdContext.nodeProductDate().getElementAt(0).getAttributeValue("Validfr").toString();
    prodElem.setValidFrom(new Date(smpdtFormat.parse(validFr).getTime()));
    Regards,
    Mithu

  • SimpleDateFormat: when day of month becomes day of week

    I have a weird situation where the SimpleDateFormat class seems to interpret the "dd" mark as day of week instead of day of month when I use a certain pattern. The following code demonstrates the problem:
    public class ByteTest {
        public static final String PATTERN = "mm HH dd MM F";
        // public static final String PATTERN = "dd MM yyyy";
        public static void main(String [] args) throws Exception {
            String str = "11 11 08 11 1";
            // String str = "24 11 2004";
            System.out.println(strToDate(str, PATTERN));
        public static Date strToDate(String date, String pattern) throws ParseException {
            SimpleDateFormat formatter = new SimpleDateFormat(pattern);
            formatter.setLenient(false);
            return formatter.parse(date);
    }The result (at least for me) is:
    Exception in thread "main" java.text.ParseException: Unparseable date: "11 11 08 11 1"
    at java.text.DateFormat.parse(DateFormat.java:335)
    at ByteTest.strToDate(ByteTest.java:20)
    at ByteTest.main(ByteTest.java:14)
    When I change "dd" from 08 to 07, I get this:
    Sat Nov 07 11:11:00 EET 1970
    ...and finally, when I change the pattern (done here by uncommenting the commented lines and commenting the ones above them), I get:
    Wed Nov 24 00:00:00 EET 2004
    So, as you can see, for some reason "dd" is interpreted as day of week number in the weirder pattern (which unfortunately we have to use in a pattern matching thing we are using). Any ideas?
    When I comment the line with setLenient(false), it also works fine, but unfortunately we need to use that flag because otherwise users could input weird values for the various fields.
    I tried adding Locale.UK to the parsing method, but that made no difference so clearly my locale (+02:00 GMT) is not at fault.
    I also considered if the day might be out of range since using this pattern we get year 1970, but clocks start counting from 1.1.1970 right? So that doesn't seem a likely cause either. :-/
    The markers for day of week in SimpleDateFormat are E and F; so I guess the question is, when does d become E or F...

    I'm not sure I quite understand what the problem is... the reason why you can't parse that date is that it's invalid, Sunday November 8 on 1970 goes to the second week of the month, so day-of-week-in-month is 2, not 1.. so the string you should pass is "11 11 08 11 2"

  • WEEK_OF_MONTH parsing in SimpleDateFormat

    Hello,
    I am trying to use the WEEK_OF_MONTH (capital W) in SimpleDateFormat. I want to be able to do both parse() and format() of in the format "yyMMWW". I also want to use false lenient in order to have strict control.
    I have seen that the first week every month (WEEK_OF_MONTH == 1) can not be parsed properly. Below is an example program demonstrating the issue.
    The program tries 100 dates from Jan 1 2006 and onwards. It converts to the yyMMWW format (which always goes fine). I also try to convert back from the yyMMWW format (using parse() method) and see that it fails on some dates.
    I get an parse exception like this:
    060204 -> 060201 -> java.text.ParseException: Unparseable date: "060201"
    060205 -> 060201 -> java.text.ParseException: Unparseable date: "060201"
    060206 -> 060202 -> 060206
    060207 -> 060202 -> 060206
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.GregorianCalendar;
    public class SimpleDateFormatIssue {
         public static void main(String[] args) throws ParseException {
              GregorianCalendar cal = new GregorianCalendar();
              cal.setFirstDayOfWeek(Calendar.MONDAY);
              cal.setLenient(false); //Strict checkin, significant for the issue
              //System.out.println(cal.getMinimalDaysInFirstWeek()); //doesnt matter what
              SimpleDateFormat fYYMMDD = new SimpleDateFormat("yyMMdd");
              fYYMMDD.setCalendar(cal);
              SimpleDateFormat fYYMMWW = new SimpleDateFormat("yyMMWW");
              fYYMMWW.setCalendar(cal);
              Date d = fYYMMDD.parse("060101");
              for (int i = 0; i < 100; i++) {
                   String outputYYMMWW = fYYMMWW.format(d);
                   Date parsedYYMMWW = null;
                   Exception exc = null;
                   try {
                        parsedYYMMWW = fYYMMWW.parse(outputYYMMWW);
                   } catch (ParseException e) {
                        exc = e;
                   System.out.println(fYYMMDD.format(d) + " -> " + outputYYMMWW + " -> " + (parsedYYMMWW != null ? fYYMMDD.format(parsedYYMMWW) : exc));
                   d = getDayAfter(cal,d);
         public static Date getDayAfter(Calendar cal, Date date) {
              cal.setTime(date);
              cal.add(Calendar.DAY_OF_MONTH,1);
              Date dayAfter = cal.getTime();
              return dayAfter;
    So I wonder, am I doing SimpleDateFormat abuse when I want to parse a yyMMWW formated string?
    Or perhaps I have a bug in my program... :)
    I saw some bugs in bug parade about SimpleDateFormat and WEEK_IN_MONTH but they all appears to be fixed in Java 5 which I am using:
    java -version
    java version "1.5.0_06"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_06-b05)
    Java HotSpot(TM) Client VM (build 1.5.0_06-b05, mixed mode, sharing)
    Thank you in advance for any pointers.
    /Anders

    The ones that fail are the ones before the first Monday of the month (since you set Monday as the first day of the week). So, I guess saying you are in the first week "060201" can't be translated back to a Monday in February.
    Not sure what to do about it, though. (I didn't look what, if anything, any bugs said about it.)

  • Can SimpleDateFormat for BC4J be used in Jdev 10g?

    I recently migrated a struts/bc4j app from Jdev 9.0.3.4, we use SimpleDateFormat quite extensivly in Entity and View Objects, however the AttributeDefImple.getFormattedAttribute method is throwing the following exception:
    Error Message: JBO-29000: Unexpected exception caught: java.lang.IllegalArgumentException, msg=Cannot format given Object as a Date
    Error Message: Cannot format given Object as a Date
    oracle.jbo.JboException: JBO-29000: Unexpected exception caught: java.lang.IllegalArgumentException, msg=Cannot format given Object as a Date
         at oracle.jbo.server.AttributeDefImpl.getFormattedAttribute(AttributeDefImpl.java:2849)
         at oracle.jbo.html.HtmlServices.getAttributeStringValue(HtmlServices.java:881)
         at oracle.jdeveloper.html.HTMLFieldRendererImpl.getHTMLValue(HTMLFieldRendererImpl.java:432)
         at oracle.jdeveloper.html.HTMLFieldRendererImpl.getHTMLValue(HTMLFieldRendererImpl.java:409)
         at oracle.jdeveloper.html.HTMLFieldRendererImpl.setValueFromRow(HTMLFieldRendererImpl.java:442)
         at oracle.jdeveloper.html.ReadOnlyField.renderToString(ReadOnlyField.java:27)
         at oracle.jbo.html.jsp.datatags.RenderValueTag.doStartTag(RenderValueTag.java:33)
         at main.jspService(main.jsp:65)
         at com.orionserver.http.OrionHttpJspPage.service(OrionHttpJspPage.java:56)
         at oracle.jsp.runtimev2.JspPageTable.compileAndServe(JspPageTable.java:569)
         at oracle.jsp.runtimev2.JspPageTable.service(JspPageTable.java:304)
         at oracle.jsp.runtimev2.JspServlet.internalService(JspServlet.java:509)
         at oracle.jsp.runtimev2.JspServlet.service(JspServlet.java:413)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.evermind.server.http.ResourceFilterChain.doFilter(ResourceFilterChain.java:65)
         at oracle.security.jazn.oc4j.JAZNFilter.doFilter(Unknown Source)
         at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:604)
         at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:317)
         at com.evermind.server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:790)
         at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:270)
         at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:112)
         at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:186)
         at java.lang.Thread.run(Thread.java:534)
    ## Detail 0 ##
    java.lang.IllegalArgumentException: Cannot format given Object as a Date
         at java.text.DateFormat.format(DateFormat.java:279)
         at java.text.Format.format(Format.java:133)
         at oracle.jbo.format.DefaultDateFormatter.format(DefaultDateFormatter.java:84)
         at oracle.jbo.server.AttributeDefImpl.getFormattedAttribute(AttributeDefImpl.java:2843)
         at oracle.jbo.html.HtmlServices.getAttributeStringValue(HtmlServices.java:881)
         at oracle.jdeveloper.html.HTMLFieldRendererImpl.getHTMLValue(HTMLFieldRendererImpl.java:432)
         at oracle.jdeveloper.html.HTMLFieldRendererImpl.getHTMLValue(HTMLFieldRendererImpl.java:409)
         at oracle.jdeveloper.html.HTMLFieldRendererImpl.setValueFromRow(HTMLFieldRendererImpl.java:442)
         at oracle.jdeveloper.html.ReadOnlyField.renderToString(ReadOnlyField.java:27)
         at oracle.jbo.html.jsp.datatags.RenderValueTag.doStartTag(RenderValueTag.java:33)
         at main.jspService(main.jsp:65)
         at com.orionserver.http.OrionHttpJspPage.service(OrionHttpJspPage.java:56)
         at oracle.jsp.runtimev2.JspPageTable.compileAndServe(JspPageTable.java:569)
         at oracle.jsp.runtimev2.JspPageTable.service(JspPageTable.java:304)
         at oracle.jsp.runtimev2.JspServlet.internalService(JspServlet.java:509)
         at oracle.jsp.runtimev2.JspServlet.service(JspServlet.java:413)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.evermind.server.http.ResourceFilterChain.doFilter(ResourceFilterChain.java:65)
         at oracle.security.jazn.oc4j.JAZNFilter.doFilter(Unknown Source)
         at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:604)
         at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:317)
         at com.evermind.server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:790)
         at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:270)
         at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:112)
         at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:186)
         at java.lang.Thread.run(Thread.java:534)
    this breaks the jbo datatags datatable and rendervalue plus some custom code I have to get the formatted dates using HtmlServices.getAttributeStringValue(...)
    So is Simple Date Format broken in 10g? Is this the wrong way to go about view/entity formatting? I don't see what I could be doing wrong, this all works fine in 9.0.3.4, I am not including any old jars from 9.0.3.4 either...any ideas?

    Problem solved.
    I was including BC4J Generic Domains library in my project. Which contains yet another implemetation of oracle.jbo.domains.Date this one is not what we want to use :) The problem arose because the IDE detected the correct Date class while the embedded server chose the wrong one, so just removed that library and I was good to go. This problem also reared it's ugly head when I tried to use the infamous FlexiDate class and it complained that it couldn't find a constructor in it's superclass that took a byte array as input.

  • Help needed in using SimpleDateFormat

    Hi,
    Here is my code ...
                  SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
                sdf.setLenient(false);
                ParsePosition pos = new ParsePosition(0);
                  Date d1 = sdf.parse("10/22/2005",pos);
                java.util.Calendar gc = new GregorianCalendar();
                gc.setTime(d1);
                  System.out.println("Year= "+gc.get(Calendar.YEAR));
                  System.out.println("Month= "+gc.get(Calendar.MONTH)+1);
                  System.out.println("Date= "+gc.get(Calendar.DAY_OF_MONTH));
                    DateFormat dateFormatter = DateFormat.getInstance();The output is
    Year= 2005
    Month= 91
    Date= 22
    Can anyone explain why Month went wrong?

    >  System.out.println("Month= "+gc.get(Calendar.MONTH)+1);You are effectively doing this:
    String monthString = "Month= " + 9;  // Month= 9
    monthString = monthString + 1; // Month= 91Do this to force the numeric addition (or, better yet, use SimpleDateFormat for formatting):
    System.out.println("Month= "+(gc.get(Calendar.MONTH)+1));This will give:
    int monthNum = 9 + 1; // 10
    monthString = "Month= " + 10; // Month= 10

  • Few questions about Calendar / SimpleDateFormat classes

    Hi.
    I have few questions about Calendar class:
    1. How can I get only date representation (without the time)?
    after doing:
    Calendar cal = Calendar.getInstance();
    I tried to clear unecessary fields:
    cal.clear(Calendar.SECOND);
    cal.clear(Calendar.MINUTE);
    cal.clear(Calendar.HOUR_OF_DAY);
    But after printing the time, it seems that the HOUR was not cleared:
    SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    System.out.println(sdf1.format(cal.getTime()));
    ---> 03/11/2004 17:00:00
    Am I missing somthing?
    2. I want to make sure that two different formats couldn't be compared. i.e., if I'll try to parse one String according to different format -- ParseException will be thrown.
    String date = "19/04/2004 13:06:10";
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Date dateObj = sdf.parse(date);
    However, even though that formats are different, no exception is thrown and the return Date is 19/04/2004 00:00:00.
    How can I cause to exception to be thrown if formats are not identical?
    Thanks in advanced

    The Calendar class has a few of what Microsoft would call 'features'. :^)
    To clear the time, call:
    calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY), 0, 0, 0);
    If you want 'pessimistic' rather than 'optimistic' date parsing, you have two options:
    1) Call calendar.setLenient(false);
    See if that is strict enough for your needs, otherwise:
    2) Write code to ensure a stricter parsing of the string passed in. For example, you could very simply check the length of the string to determine if time data is also present.
    When parsing, a string like '02/29/02' would parse to the date '03/01/02'. Setting lenient to false may fix this, but the surest way is to do some testing and then make the parsing more pessimistic where it suits your needs.
    - Saish
    "My karma ran over your dogma." - Anon

  • Change sql date to simpledateformat (mm/dd/yyyy)

    Hi All,
    I am retrieving date from the database in the following format :
    2006-08-09 09:12:14:0
    I have to change it in the mm/dd/yyyy format ..
    How can I do it in java
    answer please
    Thanks

    I am retrieving date from the database in the
    following format :Are you receiving a Date or a String? Dates don't have formats.
    2006-08-09 09:12:14:0
    I have to change it in the mm/dd/yyyy format ..Use SimpleDateFormat. The API docs explain how it's done.

  • How to convert a String into a date in yyyy-MM-dd using SimpleDateFormat?

    Hi Guys,
    I am using the following code
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    public class ValiDATE {
         private static boolean validateDateFormat(String strDate) {
              try {
                   SimpleDateFormat formatter = new SimpleDateFormat("yy-MM-dd");
                   try {
                        formatter.setLenient(false);
                        formatter.parse(strDate);
                   catch (ParseException e) {
                        // invalid date/datetime format          
                        return false;
              catch (Exception ignored) {
              return true;
         public static void main(String args[]){
              System.out.println(validateDateFormat("11111-11-11"));          
    }In the above snippet even if I pass the string parameter as "11111-11-11" it returns a new date and hence prints TRUE in the console, but I want the date to be in yyyy-MM-dd format that is no of years shouldn't exceed 4 digits in all.
    I don't want to use RegEx, I know this can be done using SimpleDateFormat, but would like to know how that can be done.
    I think it has to do something with this . ( [http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html#year|http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html#year] )
    Regards
    AR

    Java.slogger wrote:
    Yeah I have gone through the javaDoc and it says For formatting, if the number of pattern letters is 2, the year is truncated to 2 digits; otherwise it is interpreted as a number. The important part is:
    JavaDoc:
    Any other numeric string, such as a one digit string, a three or more digit string, or a two digit string that isn't all digits (for example, "-1"), is interpreted literally.
    Do you know any workarounds else is using a Regex is the best approach?I don't see this as a problem. Everything behaves as designed and as is sensible.
    So if you want to avoid dates with 5-digit numbers, I'd add something like:
    if (parsedDate.after(CUTOFF_DATE)) {
      throw new OhNoesThisIsEvilException("!");
    }

  • Need info on SimpleDateFormat, Converting String to Date

    I'm a newbie and doing a conversion of a string to a date and it's adding a little less than 11 minutes. I know I'm missing something really simple but as I read it I ought to be able to convert "20030125 084539.637696" to Sat Jan 25 08:45:39 not 8:56! Also, for the time being I'm ignoring the zulu 'Z' because I can't find a pattern that'll take it.
    System.out.println("INFO:MetadataExtractorBean::filestarttime:" + filestarttime);
    filestarttime = filestarttime.replace("Z","");
    System.out.println("after filestarttime.replace(Z,null) filestarttime:" + filestarttime);
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd hhmmss.SSSSSS");
    Date convertedDate = dateFormat.parse(filestarttime);
    System.out.println("after dateFormat.parse(filestarttime) convertedDate:" + convertedDate);
    INFO:MetadataExtractorBean::filestarttime:20030125 084539.637696Z
    after filestarttime.replace(Z,null) filestarttime:20030125 084539.637696
    after dateFormat.parse(filestarttime) convertedDate:Sat Jan 25 08:56:16 EST 2003
    Can someone help me with a) why it doesn't remain 8:45, and b) how to modify the pattern to be able to parse a zulu date. Thanks in advance.

    import java.text.*;
    public class ParsingExample {
        public static void main(String[] args) throws ParseException {
            String s = "20030125 084539.637";
            SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd HHmmss.SSS");
            System.out.println(f.parse(s));
    }Your round up was because ".637696" was taken to mean 637,696 milliseconds. SimpleDateFormat doesn't have a way to accept microseconds, and anyway, java.util.Date only has millisecond precision. I also changed "hh" to "HH" because I assume this is with a 24 hour clock.
    edit: you can tell your date format not to do these roll ups by setting:
    f.setLenient(false);

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

    Hiii...
    I am using SimpleDateFormat to do date validation and parsing. The problem that I am having is that I am setting the pattern of SimpleDateFormat to "MMddyyyy". Now, because of some implicit year validation, dates such as "121203" are taken as valid dates. I need to force the user to enter dates in (mmddyyyy) format.
    Is their any function which would force the SimpleDateFormat function to throw a parse exception for the above type (mmddyyyy) of dates.
    sanjay.

    hii..
    setLenient doesn't solve the problem. For instance the below code block doesn't throw any exception..
    java.text.SimpleDateFormat dft = new java.text.SimpleDateFormat();
    dft.applyPattern("MMddyyyy");
    dft.setLenient(false);
    java.util.Date dtObj = dft.parse("080103");
    System.out.println(dtObj.toString());
    Also, from what I have read..if setLenient is true then dates like 02302003(feb. 30th) is interpreted as Mar'2nd 2003. but by setting it to false feb.30th throws a parseException BUT it doesn't solve my problem of strict formatting.
    sanjay.

  • Displaying Date and Time using SimpleDateFormat

    I am having trouble displaying the year in a 4 digit format.
    My code is as follows:
    long measurement;     
    Calendar TimeStamp = Calendar.getInstance();
    SimpleDateFormat TimeStampFormat = new SimpleDateFormat("yyyy:dd:hh:mm:ss");
    TimeStamp.setTimeInMillis(measurement);
    System.out.print( "\n" + this.getName() + TimeStampFormat.format(TimeStamp.getTime()) + "\t" + Double.longBitsToDouble(measurement));
    The display is as follows:
    1229798184808538385     38972723:04:10:15:38     Sun Feb 04 22:15:38 EST 38972723
    1229798184808538385     38972723:04:10:15:38     Sun Feb 04 22:15:38 EST 38972723
    1229798184808538385     38972723:04:10:15:38     Sun Feb 04 22:15:38 EST 38972723
    1229798184808538385     38972723:04:10:15:38     Sun Feb 04 22:15:38 EST 38972723
    The first column is milliseconds which looks fine, the second column looks like the year is stll displayed in milliseconds, same with column 3.
    Any ideas on what the problem is?
    Thanks

    Your time has too many digits. When I print currentTimeMillis I get
    1234028242125
    You appear to have the time in nano-seconds.
    1229798184808538385
    You might get the right time if you divide by a million.

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

Maybe you are looking for

  • Why rollback is not working....

    it's 10g as far as I know, dbms_scheduler.create_job is not a DDL. So why this is saving insert ... SQL*Plus: Release 10.2.0.3.0 - Production on Sat May 10 20:58:31 2008 Copyright (c) 1982, 2006, Oracle.  All Rights Reserved. Connected to: Oracle Dat

  • Touch pad controls disappeared after update for Bootcamp windows 7

    After updating Bootcamp for Windows 7 on my MacBook Pro 13" (Mid 2009), the touchpad lost its tap functionality and there, nolonger, is a touchpad tab in the Bootcamp Manager. Is there any way to reinstate the "tap to click" function?

  • IMac i5 max ram?

    Hi - I have a new iMac (27", 3.1 i5) on the way and I'm upgrading the mempry from 4GB to 16GB. I got 2x8GB sticks from Crucial and am planning to install them in place of the 2x2GB memory that comes with the machine. My question, is there any harm to

  • Facetime forever connecting

    I can use my facetime on certain people but on my other friends, it just saying "(my friends name) is not available" I even tried some of troubleshoot that the apple support gave to me but still no luck, I even updating my iPad to iOS Bugs a.k.a iOS

  • Mail folders - how to promote, demote

    With my iMac it seems quite easy to promote and demote mail folders.  I also use a Tashiba Satelite tablet computer  running Windows 7 and access email via iCloud.  The issue I have come across with the tablet is not being able to promote or demote m