SimpleDateFormat and Milliseconds

Hi,
This is for Oracle 9i's Timestamp field.In the code, I have a java.sql.Timestamp object ,example, 2003-07-21 09:10:11.234.What Iam trying to do is to create a string with the format dd-MMM-yyyy HH:mm:ss.SSS , for the above example it would be :
21-JUL-2003 09:10:11.234
So, this is what Iam doing in the code,
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss.SSS");
String formattedValue = sdf.format(unformattedValue);
System.out.println(" unformattedValue: " + unformattedValue);
System.out.println(" formattedValue: " + formattedValue);
here, unformattedValue is the original java.sql.Timestamp object.
what I see in the output is
unformattedValue: 2003-07-21 09:10:11.234
formattedValue: 21-JUL-2003 09:10:11.0
I dont understand why the formatted isn't 21-JUL-2003 09:10:11.234
Any idea what Iam doing wrong.
Thanks,
Sunjit

Found the solution:
// trying to convert date from yyyy-MM-dd HH:mm:ss.SSS to dd-MMM-yyyy HH:mm:ss.SSS
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss.SSS");
System.out.println(" TRYING TO CONVERT: " + unformattedDate);
System.out.println(" unformattedDate.getClass(): " + unformattedDate.getClass());
int millis = (int) ((((java.sql.Timestamp) unformattedDate).getNanos())/1000000);
System.out.println("--millis: " + millis);
System.out.println("-- unformattedDate.getTime(): " + unformattedDate.getTime());
long finalstuff = unformattedDate.getTime() + millis;
System.out.println("-- finalstuff: " + finalstuff);
java.util.Date date = new java.util.Date(unformattedDate.getTime() + millis);
String dateAsAFormattedString = formatter.format(date);
System.out.println(" dateAsAFormattedString: " + dateAsAFormattedString);
OUTPUT
TRYING TO CONVERT: 2003-07-22 09:10:11.234
unformattedDate.getClass(): class java.sql.Timestamp
--millis: 234
-- unformattedDate.getTime(): 1058879411000
-- finalstuff: 1058879411234
dateAsAFormattedString: 22-Jul-2003 09:10:11.234

Similar Messages

  • SimpleDateFormat and Timestamp does not exist in the 1.6 JDK (1.6.0_18)

    I am trying to compile a program with SimpleDateFormat and I get "cannot find symbol". I'm using Netbeans and Maven and in Netbeans, the software finds the correct import java.text.SimpleDateFormat, so it's not a question of the definitions not being there, it's the compiled classes that are missing somehow.
    Any ideas what could be the problem?
    My classpath: CLASSPATH=.;C:\Program\Java\jdk.1.6.0_18\jre\lib\resources.jar;C:\Program\Java\jdk1.6.0_18\jre\lib\rt.jar;C:\Program\Java\jdk1.6.0_18\jre\lib\sunrsasign.jarI reinstalled both netbeans and the JDK (after first uninstalling them, then removing any remaining files manually and then rebooting my computer).
    This simple application demonstrates the problem:
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    public class DatabaseBuilder
        private DateFormat m_formatter;
        public DatabaseBuilder()
            m_formatter = SimpleDateFormat( "yyy-MM-dd HH:mm:ss" );
    }Resulting output:
    DatabaseBuilder.java:10: cannot find symbol
    symbol  : method SimpleDateFormat(java.lang.String)
    location: class DatabaseBuilder
            m_formatter = SimpleDateFormat( "yyy-MM-dd HH:mm:ss" );
                          ^
    1 error

    dh-at-cross wrote:
    On the internet it is easy to be misunderstood and to me your message came across much more "read the error message, stupid" than you intended I just wanted to let you know.I'm aware that it's easy to be mis-understood on the internet. But to be totally honest: that's a risk, I'm willing to take.
    The alternative is to be extremely polite in every post and add an extensive disclaimer describing my very intent in addition to the pure technical discussion.
    But I choose not to do that (and thus tolerate a (hopefully) small number of people who are offended by me) for several reasons:
    - I'm to lazy to write that disclaimer
    - writing it would cost time, which I can use better for helping others or getting some work done
    - writing that disclaimer would give people the impression that it will always be that way, but it's not true: you'll have to be able to deal with technical criticism in the technical world
    - if someone wants to feel offended, they will find a reason, no matter how polite I am

  • Help with SimpleDateFormat and time

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

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

  • SimpleDateFormater and MySql date errors

    I've looked around in the forums for an answer to this, but failed to find anything.
    I'm loading a date from a MySql (v 3.22) table and using SimpleDateFormatter to format it before I make an XML call to push it to the server. The formatter appears to fail on average 4 out of 11,000 times. The failure is "random" year, month, day, hour, minute or second. Sometimes just one of these is bad, sometimes multiples.
    The end result is a bad date record on the server and no record of it on the client. No exceptions are thrown.
    Not sure if this has anything to do with the error, but I've found that 80% of the errors occur the first time the SimpleDateFormatter is called.
    Here's some examples of what is bad vs real (yyyy-mm-dd+hh:mm:ss):
    2003-03-28+12:53:12 2003-03-25+12:53:12
    2003-03-30+07:54:38 2003-03-22+07:54:38
    2008-06-25+07:31:57 2003-03-22+07:31:57
    2003-04-21+05:12:17 2003-03-22+05:12:17
    2003-04-23+12:35:54 2003-03-21+12:35:54
    2003-04-23+07:32:49 2003-03-21+07:32:49
    Here's some snippits:
    // this gets the date from the recordset.
    // I have to typecast the date because of java.sql.Date vs java.util.Date.
    java.util.Date d = (java.util.Date) recordSet.getTimestamp("InDate");
    // Here's the method called to convert and format the date
    public static String fixDateForCorp(java.util.Date d)
    {if (d == null) return null;
    String s = null;
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd+HH:mm:ss");
    formatter.setTimeZone(java.util.TimeZone.getDefault());
    try
    {s = formatter.format(d)
    catch (Exception e)
    {// this really goes to a log
    System.out.println("ERROR, fixDateForCorp:Exception:" + e.getMessage());
    return null;
    return (s);
    } // getDateTimeStr
    Thanks in advance,
    Bit

    Thanks for responding DrClap.
    But each call to fixDateForCorp creates a new SimpleDateFormatYes, I'm grasping for straws on this one.
    Your examples are all off by an exact number of days;Here's some more examples, Sorry bad sample of data the first time.
    2005-03-25+20:07:28 2003-03-29+10:27:28
    2003-03-23+13:56:44 2003-03-29+14:17:44
    2003-03-26+22:28:11 2003-03-29+14:34:11
    2003-03-30+15:40:40 2003-03-31+14:34:40
    It is the MySQL JDBC driver that is creating those Timestamp objects, so it is possible that is where the error occurs.Interisting idea. For fun I did a toString() on the date that MySql returns, to my suprise it looked like this:
    toString:2003-04-01 14:50:08.0
    Leading zeros, just replace the space with the "+", kill the milliseconds and that should do it. Not using the formatter at all. I'm going to try this and it will nail the driver if it continues to fail.
    SimpleDateFormat is not thread-safe; are there multiple threads involved here? A flag is set to determine if the record is sent and persists the data in the MySql table. Periodically, a record set of unreplicated records is retrieved and sent to the server. I have to create a new url for each push in the record set so I'm pretty certain that multiples are not called. I've written a thread handler as well to prevent multiple calls of the replication methods.
    I'm going to try the toString() method for creating the string. I'll post here the results for anyone else having this problem. Will be a month or so before it's distributed though.
    Thanks again,
    Bit

  • SimpleDateFormat and French

    Hi,
    I use SimpleDateFormat for converting a string to Date.
    My input will be a String in MMM DD, YYYY format and I want the output in yyyy-MM-dd format.
    The piece of code I hv written works well for English, but not for French.
    My code:
         String substituteValue = "Avr 06, 2005";
         SimpleDateFormat objLaunchDateFormatTo = new SimpleDateFormat ("yyyy-MM-dd",locales);
         SimpleDateFormat objLaunchDateFormatFrom = new SimpleDateFormat ("MMM dd, yyyy",locales);
         java.util.Date objLaunchDate = null;
         ParsePosition pos1 = new ParsePosition(0);
         String strFormattedDate = null;
         try {
              objLaunchDate = objLaunchDateFormatFrom.parse(substituteValue,pos1);
              System.out.println("objLaunchDate : "+objLaunchDate);
              strFormattedDate = objLaunchDateFormatTo.format(objLaunchDate);
              substituteValue = strFormattedDate;
              System.out.println("substituteValue : "+substituteValue);
         catch (Exception eParse) {
              eParse.printStackTrace();
              System.out.println("Catch Block : substituteValue : "+substituteValue);
         }In line 1 I am giving String substituteValue = "Avr 06, 2005";
    It is not getting converted to Date object.
    But if I give it as String substituteValue = "Avril 06, 2005";
    then it works fine.
    Pls let me know whether this is the JAVA's specification as for as French language is concerned or is there anyother way by which I can achieve the reqd functionality.
    Thanks in advance. Pls help me to resolve the problem.
    Thanks & Regards,
    V.Ganessin

    Hi,
    I forgot to include one declaration statement
    Locale locales = new Locale("fr","");

  • Xp20:current-dateTime() and Milliseconds

    Hi
    Does anyone know how to obtain a dateTime to 1 tenth of a second?
    2007-07-06T09:11:48+00:00 is being returned from the above function and I need the date in the following format
    2007-07-06T09:11:48.1Z
    Many thanks
    Pete

    Hi Pete,
    Here's a sample BPEL process that fills a xs:string variable called currentDateTime with a formatted date/time string:
    <?xml version = "1.0" encoding = "UTF-8" ?>
    <!--
      Oracle JDeveloper BPEL Designer
      Created: Fri Jul 06 14:58:24 CEST 2007
      Author:  Bastiaan Schaap, Floris Automatisering
      Purpose: Asynchronous BPEL Process
    -->
    <process name="BPELProcess1"
             targetNamespace="http://xmlns.oracle.com/BPELProcess1"
             xmlns="http://schemas.xmlsoap.org/ws/2003/03/business-process/"
             xmlns:xp20="http://www.oracle.com/XSL/Transform/java/oracle.tip.pc.services.functions.Xpath20"
             xmlns:bpws="http://schemas.xmlsoap.org/ws/2003/03/business-process/"
             xmlns:hwf="http://xmlns.oracle.com/bpel/workflow/xpath"
             xmlns:ids="http://xmlns.oracle.com/bpel/services/IdentityService/xpath"
             xmlns:ldap="http://schemas.oracle.com/xpath/extension/ldap"
             xmlns:xsd="http://www.w3.org/2001/XMLSchema"
             xmlns:ehdr="http://www.oracle.com/XSL/Transform/java/oracle.tip.esb.server.headers.ESBHeaderFunctions"
             xmlns:client="http://xmlns.oracle.com/BPELProcess1"
             xmlns:bpelx="http://schemas.oracle.com/bpel/extension"
             xmlns:ora="http://schemas.oracle.com/xpath/extension"
             xmlns:orcl="http://www.oracle.com/XSL/Transform/java/oracle.tip.pc.services.functions.ExtFunc"
             xmlns:xref="http://www.oracle.com/XSL/Transform/java/oracle.tip.xref.xpath.XRefXPathFunctions">
        <!--
            PARTNERLINKS                                                     
            List of services participating in this BPEL process              
        -->
        <partnerLinks>
            <!--
          The 'client' role represents the requester of this service. It is
          used for callback. The location and correlation information associated
          with the client role are automatically set using WS-Addressing.
        -->
            <partnerLink name="client" partnerLinkType="client:BPELProcess1"
                         myRole="BPELProcess1Provider"
                         partnerRole="BPELProcess1Requester"/>
        </partnerLinks>
        <!--
            VARIABLES                                                       
            List of messages and XML documents used within this BPEL process
        -->
        <variables>
            <!-- Reference to the message passed as input during initiation -->
            <!-- Reference to the message that will be sent back to the requester during callback -->
            <variable name="inputVariable"
                      messageType="client:BPELProcess1RequestMessage"/>
            <variable name="outputVariable"
                      messageType="client:BPELProcess1ResponseMessage"/>
            <variable name="currentDateTime" type="xsd:string"/>
        </variables>
        <!--
           ORCHESTRATION LOGIC                                              
           Set of activities coordinating the flow of messages across the   
           services integrated within this business process                 
        -->
        <sequence name="main">
            <!-- Receive input from requestor. (Note: This maps to operation defined in BPELProcess1.wsdl) -->
            <receive name="receiveInput" partnerLink="client"
                     portType="client:BPELProcess1" operation="initiate"
                     variable="inputVariable" createInstance="yes"/>
            <!--
              Asynchronous callback to the requester. (Note: the callback location and correlation id is transparently handled using WS-addressing.)
            -->
            <bpelx:exec name="getFormattedCurrentDateTime" language="java"
                        version="1.4">
                <![CDATA[java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat();         
    sdf.applyPattern("yyyy-MM-dd'T'HH:mm:ss.S'Z'");         
    String formattedDate = sdf.format(new java.util.Date());         
    addAuditTrailEntry("Formatted datetime string is: " + formattedDate);        
    setVariableData("currentDateTime", formattedDate);]]>
            </bpelx:exec>
            <invoke name="callbackClient" partnerLink="client"
                    portType="client:BPELProcess1Callback" operation="onResult"
                    inputVariable="outputVariable"/>
        </sequence>
    </process>HTH,
    Bas

  • SimpleDateFormat and Daylight Savings Time

    I am trying to parse into a Date "April 15 1999" with "MMM d YYYY" using SimpleDateFormat. This string parses w/out error and the resulting Date is: Thu Apr 15 00:00:00 PST 1999. This is correct in that I am in California. The problem is that 4/15 is Daylight Savings Time in 1999. The getTimeZone result for the parent DateFormat is "SystemV/PST8PDT". I have wrestled with this for over a day now, I admit it, I need help.
    Anyone have any ideas what could be happening here?
    Thanks
    Roger

    When I run BigDaddy's code I get MST for the TZ (which is correct, my default is Mountain TZ and we don't observe DST. By this I surmise that BDLH's default is Pacific TZ and that it observes DST. The following code shows the setting of the TZ to "America/Los_Angeles" and produces the correct result. Windows XP.
    import java.text.*;
    import java.util.*;
    public class PTest {
        public static void main(String[] args) throws ParseException {
            SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy");
            Date dte = sdf.parse("April 15 1999");
            System.out.println(dte);
            SimpleDateFormat sdf2 = new SimpleDateFormat("MMM dd yyyy zzzz");
            sdf2.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
            System.out.println(sdf2.format(dte));
    }

  • Seconds and Milliseconds

    Hello all,
    I am creating a timer program that, right now, seems to work ok, except
    for a few small bugs. First off, I need to know if there is any way to
    make a thread sleep for 1000 milliseconds (I can do this) but also have
    another thread that will let me do the milliseconds. Does anyone know
    how to do this? Also, how do I stop the execution of a thread? I want the
    program to stop when the user closes the application, but I cannot seem
    to get it to stop. I have tried myThread.destroy() and myThread.yield()
    but neither seems to stop the thread and therefore the program. Any help
    at all would be enormously appreciated. Thanks in advance.

    The right way to stop a thread is to call Thread.interrupt() on it. If the thread you want to stop is blocking in a wait() or similar method (see the API docs of Thread.interrupt()) it will get an InterruptedException.
    Note that there is also a method stop() in class Thread, but it is deprecated (lookup the API documentation to read why you shouldn't use that method).
    Jesper

  • SimpleDateFormat and TimeZone; is: +0200 but must be +02:00

    Hello,
    running this code ...
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");
    System.out.println(sdf.format(new Date()));... outputs this line as expected ...
    2008-07-24T18:59:58+0200... but what i actually need is ...
    2008-07-24T18:59:58+02:00Note the additional colon in the time zone output: +02*:*00. How to get that format as described in http://www.w3.org/TR/NOTE-datetime ?
    Thanks!

    nclow wrote:
    CapM wrote:
    Yes, but it also added a "GMT", which is not allowed by the remote side (i need to format XML that follows certain restrictions).Then your problem has just become a bit larger. Read the difference between the z and the Z symbol in the sdf API documentation. What will you do when your timezone output is "EDT" as it is for me? You can't put a colon in that. You may have to do further parsing with a Z symbol to eliminate text from that output and just keep the numbers. You might want to just do a new SimpleDateFormat("Z") and then pass that to a custom parser which will manipulate it according to your requirements, then append it later.Well, i guess that one is graceful and pragmatic enough. Thanks for your suggestions @ all!

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

  • SimpleDateFormat  and months

    import java.util.Date;
    public class Test
         public Test()
              Date dd = new Date();
              java.sql.Date sqldate = new java.sql.Date(dd.getTime());
              java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("dd/MMMMMMMM/yyyy");
              String ss = formatter.format(sqldate);
                 System.out.println(ss);
         public static void main(String asdas[])
              Test t = new Test();
    }This code when compiled in JCreator Displays in console
    12/october/2006,but when I compile it in eclipse it writes in console
    12/??????/2006.
    I am also Writing Swing application with Eclipse wich displays in JTextPane
    12/oktobar/2006 in cyrillc .
    my Windows locale is Serbian (Latin)
    and I Want to Displat 12/oktobar/2006 in latin
    Cab anyone Help,Please?
    Message was edited by:
    Zak34
    Message was edited by:
    Zak34

    Yes JCreator uses JRE 1.5.0_06
    eclipse uses JRe 1.5.0_08
    is that the diference?
    any way why it is displaying monyh in Ciryllic .
    Is therre a Way to change that ?
    Window is set to Serbian(latin)?

  • SimpleDateFormat and 00.00.0000 does not work

    hi,
    i have a problem with my date-format
    i�ve created a SimpleDateFormat like this
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");now i want to parse this value "00.00.0000" that means a date that not exists, but i want to keep the format for viewing reasons.
    now when i parse it, i get the date like 01.11.2002. why this?
    any ideas?
    thx anyway
    cu Errraddicator

    what means bc?I think it is profitable to know for the purpose of calendrical calculations that Java can deal with BCE (before common era) years.
    The year "0000" is recognized as 1 BCE, "00" for MM is as December of the year before, and "00" for date as the day before the first day of the month. These implies that "00.00.0000" in you case is recognized in the following way:
        1 day before the first day of the month one month before January of the year 1 BCE
       => 1 day before the first day of December 1, 2 BCE
       =>  30 November, 2 BCE.Unless otherwise indicated, "BC" is not printed out.

  • SimpleDateFormat chopping milliseconds

    Hi,
    This is for Oracle 9i DB's Timestamp field. In the code,I have a java.sql.Timestamp object ,example, 2003-07-21 09:10:11.234.What Iam trying to do is to create a string with the format dd-MMM-yyyy HH:mm:ss.SSS , for the above example it would be :
    21-JUL-2003 09:10:11.234
    So, this is what Iam doing in the code,
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss.SSS");
    String formattedValue = sdf.format(unformattedValue);
    System.out.println(" unformattedValue: " + unformattedValue);
    System.out.println(" formattedValue: " + formattedValue);
    here, unformattedValue is the original java.sql.Timestamp object.
    what I see in the output is
    unformattedValue: 2003-07-21 09:10:11.234
    formattedValue: 21-JUL-2003 09:10:11.0
    I dont understand why the formatted isn't 21-JUL-2003 09:10:11.234
    Any idea what Iam doing wrong.
    Thanks,
    Sunjit

    Cross-posted here: http://forum.java.sun.com/thread.jsp?thread=425434&forum=31&message=1892111

  • Convert milliseconds to formatted data in JAVA

    hi all,
    i want to convert my time in milliseconds to HH:MM:SS:sss format ,
    i use ;
    Date date = new Date(timeInMills);
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss:SSS");
    String s = sdf.format(date.getTime());
    but it gives me: 02:00:00:150 instead of 00:00:00:150
    i think it is about the TimeZone. What can i do to prevent this.?

    If you insist on doing it this way, then read the API docs for SimpleDateFormat, and the class(es) from which it inherits closely, as one of them contains a method for setting the timezone, which don't you think it would be a good idea to set the timezone to GMT/UTC rather than worrying about any local timezone effects?

  • Java.text.SimpleDateFormat  with zones

    Hi,
    I have a log file which has a date format as below:
    20091224060656.000000+060
    Wondering if java.text.SimpleDateFormat would be able to parse it properly.I was seeing this API and it didnot have any exact syntax for parsing this kind of date format.
    Please let me know.
    Regards
    Sayan

    sayanb wrote:
    Hi,
    Thank you for the response.The problem is this is one our client's log file which we are trying to parse using the java.text.SimpleDateFormat from our own java application.
    Hence not sure about +060. I guess the part after the . represent the zone , please correct me.But +060 not sure what this means and I dont think java.text.SimpleDateFormat has a way to parse this.
    Please let me know your comments.Uhm, you need to "tell" SimpleDateFormat what the format is, if you don't know how to interpret the format, how are you going to be able to configure SimpleDateFormat. Contact your "client" and make sure you understand the format, then look at the API docs for SimpleDateFormat and hammer out a pattern string for that format. (But I would assume that the "part after the dot" is second fragments (smaller than milliseconds but larger than nanoseconds, about half-way between, what the name for that is, I'm not sure), and that the part with the "plus" is the timezone, probably +060 is the same as +0600.) IOW, you will probably have to "preprocess" the string removing the last three digits before the "plus" and adding a 0 to the end, but that is only a guess.

Maybe you are looking for