Date Formatting, Converting from String to Timestamp

I am trying to convert a string date to timestamp.
I have tried a couple of different ways to arrive at the end result.
I am basically trying to convert a date in the "dd-MM-yyyy" format to a timestamp.
If I use the following code, I get a date like this "18-May-2004 12:00:00 AM".
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy);
Date dContractDate = sdf.parse("18-05-2004");
long dateInMilli = dContractDate.getTime();
bHelp.bcontractdate = new Timestamp(dateInMilli);
How can I make this code display the current time not midnight or some defaulted value?
Thanks.

I think a clever person would reuse their Date.classObject and call Date.setTime() as opposed to always
rolling out a new Date()
Not really a question of cleverness. Your code wins
nothing. Objects are not magically created and garbage collected in the ether.
The cost of creating a Date is nothing
compared to the cost of a format() call. True, but not valid a valid statement pertaining to the issue which is
"does always rolling dates suffer a performance hit?"
Plus you lost clarity Maybe you loose track of your code if you don't make new Objects all the time,
but I have never suffered from this.
Why do you think Sun provided the setDate() method?
and thread-safety.I have only had Thread issues when I didn't program them properly.
Luckilly I always program the correctly ;) (Touch wood)
The facts as I seem are thus:
Rolling new dates on a 1.83 GHZ PC incurrs on average
a 19% penalty. Here is the proof.
Save this program and save it as DateTest.java
If you don't want to waste the time here are the results of running it
through the default 10 iterations.
Running 10 iterations.
Reuse of dates is 27% more efficient
Reuse of dates is 17% more efficient
Reuse of dates is 18% more efficient
Reuse of dates is 20% more efficient
Reuse of dates is 20% more efficient
Reuse of dates is 17% more efficient
Reuse of dates is 17% more efficient
Reuse of dates is 20% more efficient
Reuse of dates is 20% more efficient
Reuse of dates is 18% more efficient
Gaining "nothing " actually = 19% on average
Low percent diff = 17 High percent diff = 27
Run it 100 times and it should still be around 19%
With the hi time being about 47% (Probably the result of garbage collecting)
//////////////////////////////////// <PROOF> ///////////////////////////////////////
import java.util.Date;
public class DateTest
DateTest()
public int run()
int percent = 0;
int loopCount = 0;
Date date = null;
int z=0;
long start1=0,end1=0,start2=0,end2=0,now=0;
int time1 = 0,time2 = 0;
   now = System.currentTimeMillis();
   date = new Date(now);
   loopCount = 10000000;
   start1    = System.currentTimeMillis();
   for(z=0;z<loopCount;z++)
      now = System.currentTimeMillis();
      date.setTime(now);
   end1 = System.currentTimeMillis();
   start2    = System.currentTimeMillis();
   for(z=0;z<loopCount;z++)
      now   = System.currentTimeMillis();
      date  = new Date(now); // use 'now' so test loops are =.
   end2 = System.currentTimeMillis();
   time1 = (int)(end1 - start1);
   time2 = (int)(end2 - start2);
   percent = ((time2-time1)*100/time2);
   System.out.println("Reuse of dates is "+percent+"% more efficient");
   return percent;
public static void main(String args[])
int z=0;
int lowP=100,hiP = 0;  // lowpercent/highpercent
DateTest d = new DateTest();
int loopCount = 0;
long totals   = 0;
int average   = 0;
int values[];
int retVal = 0;
   try // Yea olde Lazy person's command line handler :)
      loopCount = Integer.parseInt(args[0]);
   catch(Exception any)
      loopCount = 10;
   if(loopCount == 0)
      loopCount = 10;
   values = new int[loopCount];
   System.out.println("Running "+loopCount+" iterations.");
   for(z=0;z<loopCount;z++)  //
      retVal = d.run();
      if(lowP > retVal)
         lowP = retVal;
      if(hiP < retVal)
         hiP = retVal;
      values[z] = retVal;
   for(z=0;z<loopCount;z++)
      totals += (long)values[z];
   average = (int)(totals/loopCount);
   System.out.println(" Gaining \"nothing \" actually = "+average+"% on average");
   System.out.println("Low percent diff = "+lowP+" High percent diff = "+hiP);
}////////////////////////////////// </PROOF> /////////////////////////////////////////
Your "nothing" is in fact on average about a 19% performance hit. per call.
These inefficiencies build up and java is infested with the,
Was it not so the java would run much more efficiently than it now does.
Ask yourself; why did Sun supply the setDate() method???
(T)

Similar Messages

  • Convert from String data type to Character data type

    Hi...,
    I'm a beginner. I try to make a program. But I don't know how to convert from string to data type. I try to make a calculator with GUI window. And when somebody put "+" to one of the window, I just want to convert it to Character instead of String.
    Sorry of my bad english..
    Please help me....
    Thanks

    String s = "a+b";
    char theplus = s.charAt(1);

  • Date format convert error in XML interface based Adobe interactive forms

    Hi experts,
    I am using XML interface based Adobe interactive form in Web Dynpro ABAP. The form just contains some date fields and numeric fields.
    When I test the WD Application, the date fields appear like 0000-00-00 at the first time. And then I set the form input disable, and get the XML from the form, at the same time I get the warning message, 'date format convert error'. By the way, I have set the edit pattern, display pattern and data pattern  of the date field to YYYYMMDD, but there seems no effect.
    Could you tell me how to set the default date format in date field Or clear the 0000-00-00?
    And another question, all of the numeric fields in the form appear like 0.0, how can I set it to empty when the form initialize?
    Best Regards,
    Guo Guo Qing

    Hi Chintan,
    Thank you for your reply.
    I have tried every possible changes on the Date field, locale, pattern. But still no effect. When the PDF come up in the WDA program, the date field is still '0000-00-00', and then I export the XML date of the form, there is also '0000-00-00' in the interface field.
    I can't clear the '0000-00-00' in initializiation event using javascript because if I need to open the form again, if I do this, the value user input could be cleared.
    I also try using Javascrip like this
    if this.rawValue == "0000-00-00"
    { this.rawValue = ""; }
    The code above can't clear the initializiation zeros too.
    Have you used the XML interface based online Adobe Forms? I have used XML PDF forms for output before, that's perfect. But the input forms seems so strange.
    Best Regards,
    Guo Guo Qing

  • Convert from String to HashMap

    Hi
    Can any body pls tell us how to convert from String to HashMap
    I have one string str="Col1=200, Col2=225";
    So how can i convert that string varibale into HashMap?

    Hi
    Can any body pls tell us how to convert from String
    to HashMap
    I have one string str="Col1=200, Col2=225";
    So how can i convert that string varibale into
    HashMap?
    Map map = new HashMap();
    String[] parts = str.split(", ");
    for (int i = 0; i < parts.length; ++i) {
        String[] entry = parts.split("=");
    map.put(entry[0], entry[1]);

  • Convert from String to Int

    Hi,
    I have a question.
    How do I convert from String to Integer?
    Here is my code:
    try{
    String s="000111010101001101101010";
    int q=Integer.parseInt(s);
    answerStr = String.valueOf(q);
    catch (NumberFormatException e)
    answerStr="Error";
    but, everytime when i run the code, i always get the ERROR.
    is the value that i got, cannot be converted to int?
    i've done the same thing in c, and its working fine.
    thanks..

    6kyAngel wrote:
    actually it convert the string value into decimal value.In fact what it does is convert the (binary) string into an integer value. It's the String representation of integer quantities that have a base (two, ten, hex etc): the quantities themselves don't have a base.
    To take an integer quantity (in the form of an int) and convert it to a binary String, use the handy toString() method in the Integer class - like your other conversion, use the one that takes a radix argument.

  • Convert from String to boolean ??

    hi everyone..
    is there any way to convert from String (as a class) to boolean (as a primitive type) ?
    thunx

    I used : Boolean.valueOf(s).booleanValue(); ,I got the same error.What same error? Surely not this one:
    cannot resolve simple in parseBoolean method??
    equals is OK, but I think it is not convert method,
    the prev. solutions by equals don't convert the value of s (String).Yes it does, for any reasonable definition of "converts". In fact, that is essentially how parseBoolean() is implemented. From the JDK 5.0 source code, class java.lang.Boolean:
         return ((name != null) && name.equalsIgnoreCase("true"));

  • Convert from String to Long

    Hello Frineds I want to convert from String to Long.
    My String is like str="600 700 250 300" and I want to convert it to long and
    get the total value in to the long variable.like the total of str in long varible should be 1850.
    Thank You
    Nilesh Vasani

    Maybe this would work?
    StringTokenizer st = new StringTokenizer(yourString, " ");
    long l = 0;
    while(st.hasMoreTokens()) {
        l += Long.parseLong(st.nextToken()).longValue();
    }

  • Convert from String to float

    How do I convert from String to float?

    Hi,
    you can use a Double for example - assuming value is that string to parse
    float f;
    try { Double d = new Double(value); f = d.floatValue(); }
    catch (NumberFormatException e) { f = 0.0; } // error - string value could not be parsed
    // here use your float fHope, that helps
    greetings Marsian
    P.S.: the Double class is usefull for that, because you also can get intValue(), doubleValue() or longValue() out of it for example. The StreamTokenizer for example parses numbers also only to double.

  • Date range converted to String format?

    Simple question:
    When I was an avid Crystal Reports 8.5 developer, I remember there was something that converted a Date Range to a string, which contained the character "[" for inclusive and "(" for exclusive and looked something like this:
    "(2/24/08...3/15/09]"
    What was that function again please?

    HI,
    Please try this link if this what you meant ? [Click Here |http://www.crystalreportsbook.com/Forum/forum_posts.asp?TID=1662&PN=1]
    Try the DTStoDate function,
    DateTime Strings
    DTSToDate({DateTime String})
    The DTSToDate({DateTime String}) function extracts the date from a
    DateTime string field.
    Hopes this is the one!
    Regards,
    Clint

  • "scan from string" to timestamp doesn't work for 18:00:00 (6PM)

    I just found a strange issue in LabVIEW.  I hope I'm doing something silly, but I just may have found an unusual bug.
    run the snippet below with the following for the input string: 03:00:00,18:00:00,17:00:00
    Time converts fine for just about any other time EXCEPT 18:00:00 (6 PM) for which it is returned as 00:00:00 (midnight). If you even add a second to it (18:00:01) you get back the expected result.
    Here's hoping I'm not loosing my mind
    Matt Holt
    Certified LabVIEW Architect
    Solved!
    Go to Solution.
    Attachments:
    TimeParseBug.vi ‏11 KB

    As annoying as it may seem, this exact scenario is an abuse of the timestamp. A timestamp is meant to be used for absolute times. And that includes a date. As Ravens Fan already pointed out, the 0 seconds since January 1, 1904 GMT is used in all timestamp display routines to mean the canonical invalid timestamp and hence the timestamp control displays the default string indicating the actual date/time format rather than a specific date/time.
    If you need an absolute timestamp, for instance because you do want to have a local time indication, although the date is not relevant, adding an offset of 86400 to all values would fix it once and for all. Now the timezone offset can't cause the timestamp to reach 0 ever, even if you reside west of GMT, and it will be fine (until you start to do timestamp arithmetic that involves subtraction of relative timespans, then you would have to make the offset big enough that this will never get an issue). The current date would serve as a nice offset for that, which would be MattH's last suggestion. Nice to see that the Scan from String routine actually does use the passed in timestamp as default value and only replaces the values it is configured to parse.
    Rolf Kalbermatter
    CIT Engineering Netherlands
    a division of Test & Measurement Solutions

  • Strange "Scan From String" to Timestamp Error

    hi,
    i am trying to parse my time-string into a Time Stamp with "Scan From String" but i get some strange Error(1).
    The Code:
    The Error:
    can anyone confirm? do i have an error in my parser-string?
    is it possibly related to this Bug
    461196
    Scan From String VI returns Error 1 with "%t" as the format string input
    http://www.ni.com/product-documentation/52151/en/
    that should be fixed?
    my labview version is
    LV 2014 Service Pack 1 -- Version 14.0.1 (32bit)
    with the RealTime addon (but the code in question was not run on RT)
    thanks for your time.
    Solved!
    Go to Solution.

    Why do you have the square brackets around the scan from string format string? They are not there when you generate the timestamp string so it will fail when trying to convert it back as they are expected to be there.
    Certified LabVIEW Architect, Certified TestStand Developer
    NI Days (and A&DF): 2010, 2011, 2013, 2014
    NI Week: 2012, 2014
    Knowledgeable in all things Giant Tetris and WebSockets

  • Problem with date format convertion

    Dear All, i want to convert the current system date to particular format that i have specified below in SimpleDateFormat but when ever i exceute my program it comes in different format
    could you help me to solve the problem
    DateFormat sdf = new SimpleDateFormat("yyyy.MM.dd hh:MM:ss");
    Date today = Calendar.getInstance().getTime();
    String rdate = sdf.format(today);
    Date date = sdf.parse(rdate);
    System.out.println("Current date and time is: "+date);i want my date to be like: *2008.09.11 05:00:17*
    but the program output is: Current date and time is: Thu Sep 11 05:00:17 EEST 2008
    thanks

    shamilsons wrote:
    Dear All, i want to convert the current system date to particular format that i have specified below in SimpleDateFormat but when ever i exceute my program it comes in different format
    could you help me to solve the problem
    DateFormat sdf = new SimpleDateFormat("yyyy.MM.dd hh:MM:ss");
    Date today = Calendar.getInstance().getTime();
    String rdate = sdf.format(today);
    Date date = sdf.parse(rdate);
    System.out.println("Current date and time is: "+date);i want my date to be like: *2008.09.11 05:00:17*
    but the program output is: Current date and time is: Thu Sep 11 05:00:17 EEST 2008
    thanksA java.util.Date is just a long. So when you said "System.out.println("Current date and time is: "+date);" you called the "toString()" method of java.util.Date, which formats it to a String the way you see. You have the date formatted the way you want in the "rdate" String, so try "System.out.println("Current date and time is: " + rdate);" and see if that works out for you.

  • Reg : date format conversion from dd.mm.yyyy to mmddyyyy

    hi ALL,
    is there any function module which can convert date format
    from <b>dd.mm.yyyy to mmddyyyy</b>.
    Thanks in advance

    Hi,
    Please check the following
    CONVERSION_EXIT_PDATE_INPUT Conversion Exit for Domain GBDAT: DD/MM/YYYY -> YYYYMMDD
    CONVERSION_EXIT_PDATE_OUTPUT Conversion Exit for Domain GBDAT: YYYYMMDD -> DD/MM/YYYY
    SCA1 Date: Conversion
    CONVERSION_EXIT_IDATE_INPUT External date INPUT conversion exit (e.g. 01JAN1994)
    CONVERSION_EXIT_IDATE_OUTPUT External date OUTPUT conversion exit (e.g. 01JAN1994)
    CONVERSION_EXIT_LDATE_OUTPUT Internal date OUTPUT conversion exit (e.g. YYYYMMDD)
    CONVERSION_EXIT_SDATE_INPUT External date (e.g. 01.JAN.1994) INPUT conversion exit
    CONVERSION_EXIT_SDATE_OUTPUT Internal date OUTPUT conversion exit (e.g. YYYYMMDD)
    TB01_ADDON
    CONVERSION_EXIT_DATEX_INPUT
    CONVERSION_EXIT_DATEX_OUTPUT
    Hope this would surely help you out.
    Thanks and regards,
    Varun.

  • Date format conversion from MySQL

    Hi my dear friends. I have some problem with the date format.
    I am using MySQL version 3, LabSQL and Labview7.1
    In the MySQL, the date format reads as 2006-12-18 14-51-25
    while, when querying in Labview, it reads 18-Dec-06 14-51-25.
    So when using this date (18-Dec-06 14-51-25) to query further. I got problems as MySQL does not recognise this format.
    How can I convert 18-Dec-06 to 2006-12-18?
    It might sound easier to change but for the year how do I change it to proper 2006, not 1906?
    Your solution will be helpful. Thanks in advance.
    Clement

    astroboy wrote:
    Hi Ravens. I think that not all computers have the same settings. Is there a way how can make sure that it still works despite of different settings in esch PC?
    By auto-changing registry?
     Clement
    There probably is a way to do that, but I don't know how.  I don't think it is a good idea to change the PC settings in that way because it would interfere with all other programs on the PC.  Suppose the user wants the format of date and time to remain the way it is for other programs or looking at file/directory properties.
    Rather than basing your functions on the system format settings, use the format string functions within labview that will make the date/time to appear the way you want it to.  Look at the format date/time string function on the timing palette.  Also, format into string on the string palette.

  • Date Format Conversion from MM.DD.YYYY to YYYYMMDD

    Hi All,
    I am trying to load data from r/3, and i have date format as MM.DD.YYYY in source system.how can i convert this into YYYYMMDD format in transfer rules(I know that we have to write a routine in transfer rules).Could anybody help me out pl?..pl give me conversion routine for it.
    Here BW Filed is 0DATE and R/3 Filed is ZZDATE.
    regards
    murali.
    Message was edited by: Murali

    Hi,
    Try to under stand what I am asking :
    <b>What is the domain(or data type) used for the ZZDATE field.</b>
    Ok ,
    If some records are having proper format and others are having wrong format, even we canot correct this with routine also. So in this case you have to edit manually at PSA, then do upload.
    You are right, when we are populating data to ODS , if there is any wrong format of value, it will not disply the error at the time of loading .It will through the error at the time of activation.
    With rgds,
    Anil Kumar Sharma .P

Maybe you are looking for

  • How can I print out contact list showing info for contacts?

    How can i print out my contact list showing info. (phone #, email address, etc.)

  • How do you get the Genius Sidebar back on iTunes 11

    How do you get the Genius Sidebar back on iTunes 11.  How is clicking on a arrow that sometimes you miss and it wants to rename the file an improvement.  then I have to click 3 times deep to get to the hidden genius recommendations? Again explain to

  • WE20 - post processing: permitted agent tab

    Hi , I need to create a inbound TXTRAW message type for a comapny code which I have done. Then in the screen where you give the process code , the next tab is post processing: permitted agent tab ... here my requirement is that this mail should go to

  • Re: How to interpret firewall log?

    I am presently employing advanced firewall settings on my iMac G5 running Tiger 10.4.7, i.e., block udp traffic, enable firewall logging, and enable stealth mode. When I opened the firewall log for the first time today, I realized I didn't know what

  • Table component grid color option

    hello, i'm curious what this option is suppose to do. i have the show grid option checked, and change the color on the grid color option. when i view the grid, i don't see any difference, so i don't know what this option is suppose to change. any hel