How to convert a string to date object?

I have a string user input for date.
I want to convert it to Date object to insert it in database.
How to do it?

Check the java.text.SimpleDateFormat class. You can use it for parsing dates. API contains good description how to build the format pattern.
HTH
Mike

Similar Messages

  • How to convert a string to date and then compare it with todays date???

    Hello.
    I want to set a format first for my dates
    DateFormate df = new SimpleDateFormate("yyyy-mm-dd");
    once this is done then I want to convert any string to date object in the above formate
    String str="2001-07-19";
    Date d = null;
    try{
    d = df.parse(s);
    }catch(ParseException pe) {
    pe.printStackTrace();
    First of all there is something wrong above,cus what I get for this is
    Fri Jan 19 00:07:00 MST 2001
    where as it should have been
    2001-07-19... to my understanding.
    once this part is done I need to get current date in the above set format and compare the
    current date and the date I set.
    I will appreciate the help.
    Thanks

    for the output part:
    a date is a point in time
    the output depends on the format you specify for output
    using for example a SimpleDateFormat.
    You only specified the format for parsing (which is independent for that of output) so java uses some default format ... see the DateFormat.format() method for details.
    for the comparison stuff, I just posted a little code snippet in this forum a few minutes ago.
    the hint is: Date.getTime() returns milliseconds after a fixed date
    hth Spieler

  • How to convert a string into an objects name?

    Hi
    I have the following problem;
    I have a string
    String a = "e1"
    and a method
    call(Event e1) that calls the "Event" class with object the name of the string a.
    How can I convert the strings name into an object so as to use it in the "call" method?
    Any ideas?
    Thanks in advance

    I don't know if this helps you, but you can do things like this.
    String a = "com.example.SomeEvent";
    //Instantiate com.example.SomeEvent
    Object o = Class.forName(a).newInstance();SomeEvent must have a non-argument constructor for this to work.
    Class that will be instantiated depens on runtime value of String a, and can be different across different executions of the program.

  • How to convert a String to Date format?

    the user enter a date in string format and the date is save in the database.
    The problem i am facing is i want to change from String to Date format.
    Here is my codes:
            public boolean insertData() throws Exception {
            boolean validFlag = false;
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            Date d = df.parse("05/18/05");
            String MY_DATE_FORMAT = "yyyy-MM-dd";
            String jobAdvertisementDate = new SimpleDateFormat(MY_DATE_FORMAT).format(d);
            String sql = "INSERT INTO companyjob (CompanyID,JobID, JobAdvertisementDate ) " +
                    " VALUES ('" + companyID + "','" + jobID + "', '" + jobAdvertisementDate + "')";
            System.out.println(sql);
            validFlag = executeSQL(sql);
            return validFlag;
        }The date is save under jobAdvertisementDate.
    My netbeans shows an error. There's a red line under DateFormat and parse inside my codes.
    PLease help me. Reply asap!!

    BebeGirl wrote:
    My netbeans shows an error. There's a red line under DateFormat and parse inside my codes.
    Red Line? Sounds ominous. I wonder what it means.
    So...what does the error say?

  • How to convert a String to Date?

    i have a String "1998-12-31" i would like to convert it to Date so that i can compare the Date in Mysql.
    i am appreciate for your help.
    Thanks
    yuetni Swee

    hi,
    i try to change the code by using the code below do you think it is ok
    i just use the Date.valueOf(String s) method. is it still working in sql?
              java.sql.Date PickDat = java.sql.Date.valueOf(PDate);
              java.sql.Date DropDat = java.sql.Date.valueOf(DDate);
              System.out.println("IN CARINFO FUNC." + pickdropPnt + PDate + DDate + carclass);
                   sql.append("SELECT * FROM CARS");
                   sql.append("WHERE TO_DAYS('" PickDat "') BETWEEN TO_DAYS('FROM_D') AND TO_DAYS('UNTIL_D') ");
                   sql.append("AND TO_DAYS('" DropDat "') BETWEEN TO_DAYS('"+PickDat+"') AND TO_DAYS('UNTIL_D') ");
                   sql.append("AND PICK_UP_DROP ='" + pickdropPnt +"' ");
                   sql.append("AND CAR_TYPE ='"+carclass + "'");

  • How to convert a string to date using OLEDB function?

    Is there any function similar to OCIDateFromText()?
    I have to read the date from a text file and store it in the sql database in a date column.
    Please suggest how to do it?
    Thanks in Advance.

    In addition, SQL Server 'likes' YYYYMMDD format to operate with dates.
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • How to convert a string value to date

    Dear All,
    I am new to powershell script, i was trying to store a Ad user password set date to a variable add, add a number of days to get the expire date.
    but when i try to convert the variable to date value, I am getting the error as below.
    Please help me......
    PS C:\script> $passwordSetDate = (get-aduser user1 -properties * | select PasswordLastSet)
    PS C:\script> $passwordSetDate
    PasswordLastSet
    7/15/2014 8:17:24 PM
    PS C:\script> $a = [datetime]::ParseExact($passwordSetDate,"MM/dd/yyyy HH:MM:SS", $null)
    Cannot find an overload for "ParseExact" and the argument count: "3".
    At line:1 char:1
    + $a = [datetime]::ParseExact($passwordSetDate,"MM/dd/yyyy HH:MM:SS", $null)
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [], MethodException
        + FullyQualifiedErrorId : MethodCountCouldNotFindBest
    PS C:\script> $a = [datetime]::ParseExact($passwordSetDate,"MM/dd/yyyy HH:MM:SS", $null)

    Dear All,
    I am new to powershell script, i was trying to store a Ad user password set date to a variable add, add a number of days to get the expire date.
    but when i try to convert the variable to date value, I am getting the error as below.
    Please help me......
    PS C:\script> $passwordSetDate = (get-aduser user1 -properties * | select PasswordLastSet)
    PS C:\script> $passwordSetDate
    PasswordLastSet
    7/15/2014 8:17:24 PM
    PS C:\script> $a = [datetime]::ParseExact($passwordSetDate,"MM/dd/yyyy HH:MM:SS", $null)
    Cannot find an overload for "ParseExact" and the argument count: "3".
    At line:1 char:1
    + $a = [datetime]::ParseExact($passwordSetDate,"MM/dd/yyyy HH:MM:SS", $null)
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [], MethodException
        + FullyQualifiedErrorId : MethodCountCouldNotFindBest
    PS C:\script> $a = [datetime]::ParseExact($passwordSetDate,"MM/dd/yyyy HH:MM:SS", $null)
    In your post you ask how to convert a string value to a date.  The value returned from the Get-AdUser is already a date.  It does not need to be converted.
    Bill has sshown one way to convert a date to a string and there are other methods.  You need to clarify your question.
    If you are really trying ot convert strings to dates then you can start with this:
    [datetime]'01/21/1965 13:33:23'
    Most date strings aer autodetected by the class.
    ¯\_(ツ)_/¯

  • How to convert a String("yyyy-mm-dd") to the same but in Date format ?

    Hi,
    can anyone plz tell me how to convert a String to a date format.I'm using MSACCESS database.I want to store this string in the database.So i need to convert it to a date format since the table is designed such a way with date/time type for date field.I used SimpleDateFormat ,but i can't able to convert.The code is given below:
    coding:
    public String dateconvertion(String strDate)
    try
    SimpleDateFormat sdfSource = new SimpleDateFormat("yyyy-MM-dd");
    Date date = sdfSource.parse(strDate);
    SimpleDateFormat sdfDestination = new SimpleDateFormat("yyyy-MM-dd ");
    strDate = sdfDestination.format(date);
    catch(ParseException pe)
    System.out.println("Parse Exception : " + pe);
    return(strDate);
    }

    i used prepared statement even now i am getting error like this.....
    i have included the prepared statement package also...
    my coding:
    ResultSet rsdatetemp = null;
    PreparedStatement ps = null;
    String query ="select distinct itemcode from sales where bill date between ? and ?";
    ps = precon.prepareStatement(query);
    ps.setDate(1,d1);//d1 and d2 are in date format
    ps.setDate(2,d2);
    rsdatetemp = ps.executeQuery();
    error :
    symbol : method setDate(int,java.util.Date)
    location: interface java.sql.PreparedStatement
    ps.setDate(1,d1);
    symbol : method setDate(int,java.util.Date)
    location: interface java.sql.PreparedStatement
    ps.setDate(2,d2);

  • Problem in converting the String to Date with time zone GMT

    Hi,
    When I tried to convert the string 12/05/2009 to Date, the time zone is set to BST.On the other hand, for the date 12/12/2009, the time zone is set to GMT. What should I do to get the time zone as GMT all the time.?
    SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
    String dateString = "12/05/2009";
    System.out.println(myDate.toString());

    I think you are all missing the point. java.util.Date objects always alway always store the date as the number of milliseconds since 1/1/1970 UTC so the only TimeZone they have its the implicit UTC. When you use the Date.toString() method the toString() method gets the default time zone from your environment and formats the data accordingly. This means that the same Date object will, by default, produce a different result for France and Australia and the US.
    So, if you have the date "12/5/2009" as a String then to convert it to a java.util.Date you must specify what TimeZone is implied. If it is your system time zone then you can just create a SimpleDateFormat object with the correct format and then use the parse() method to create the java.util.Date object and this will automatically be converted to UTC. If the date String represents some other time zone then you must explicitly set the time zone of the SimpleDateFormat object before parsing the string.
    The same approach applies when converting a java.util.Date object to a String. If you want anything other than your system time zone then you must explicitly tell the SimpleDateFormat what time zone you want the result formatted for.

  • I need help to convert a string to date and time

    Good aft,
    1.How can i get a date from the user input thro' Frames?
    2.How to parse it to the date object(I need to include java.util.Date but for the database i need to include java.sql.*,if i do so, i have error as
    found:java.util.Date
    Required:java.sql.Date)
    3.How to insert into the database
    The same i need help to insert time into database?
    I need solution and explanation...
    Reply me immediately...
    If u send me the code, its better to me.

    Hello,
    The best way is to use the HEX to decimal coversion VI in the string pallette. Then, write this decimal directly to your chart. If you are doing it a point at a time put it into a while loop.
    Doug

  • Date string to Date object

    Hi
    How would i go about parsing some date strings in DD/MM/YYYY
    format into a date objects. I am sure its an easy problem but i
    cant find a simple way to do it as most of the API's want it a
    differnt format like MM/DD/YYYY
    Thanks for any help

    Hi,
    in the actionscript 3.0 cookbook there is a class DateFormat
    described, which allows to parse strings to date objects.
    You can download the code of the dateformat.as from here .
    http://www.rightactionscript.com/ascb/
    best regards,
    kcell

  • How to convert a String to an Icon

    Hello,
    I'm trying to figure out how to convert a String (specifically one letter) to an Icon for a JTree. The program I am working on uses .png files for the icons at the moment, with each .png being a single uppercase letter. However, recent discussion has us wanting to change to something more dynamic, since we anticipate needing new letters in the near future.
    My task is to modify the current codebase so that the Icons used to identify nodes in the tree are created from a Font within code, rather than reading in .png files. I have done some experimenting with creating a Label with just that String, setting the font and trying to extract the image using calls like createImage(int width, int height) and so on, but so far to no avail.
    If I could figure out how to at least convert the String to an image, I could probably make it work (since I can play around with creating an ImageIcon with that image). Thanks in advance for any help.
    Allan

    Here is some quick and dirty code:
    import java.awt.*;
    import javax.swing.*;
    public class BasicIcon implements Icon {
        private String text;
        public BasicIcon(String text) {
            this.text = text;
        public int getIconWidth() {
            return 16;
        public int getIconHeight() {
            return 16;
        public void paintIcon(Component c, Graphics g,  int x, int y) {
            Color old = g.getColor();
            g.setColor(c.getForeground());
            g.drawString(text, x, y+13);
            g.setColor(old);
        public static void main(String[] args) {
            JPanel cp = new JPanel();
            for (char ch = 'A'; ch < 'F'; ++ch) {
                cp.add(new JButton("letter " + ch, new BasicIcon(String.valueOf(ch))));
            JFrame f = new JFrame("BasicIcon");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setContentPane(cp);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    }One thing that could be improved is the vertical positioning of the letter in the Icon.
    The x,y values passed into paintIcon are the upper-left hand corner of the icon,
    but the y value needed by drawString is the position of the String's baseline.
    To do it right, use one of Font's getLineMetrics methods and play around with ascent.

  • How to convert a string from upper case to lower case in FOX formula

    Hi Experts,
    How to convert a string from upper case to lower case in FOX formula?
    Thanks,
    Cheers!!!
    PANKAJ

    The last result.append( c ) should be:
    result.append( Character.toLowerCase(c) );

  • How to convert a string from lower case to upper case withour using transla

    Hi all,
    how to convert a string from lower case to upper case withour using translate,
    Thanks in Advance,
    Reddy

    Refer to this related thread
    Re: hi guys this very urgent please help

  • How to convert Flat file(.txt) data to an Idoc format(ORDERS05)

    Hi,
    How to convert Flat file(.txt) data to an Idoc format(ORDERS05). If any FM does the same work please let me know.
    thanks in advance,
    Chand
    Moderator message : Duplicate post locked. Read forum rules before posting.
    Edited by: Vinod Kumar on Jul 26, 2011 11:11 AM

    Hi,
            For more information, please check this link.
    http://sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/46759682-0401-0010-1791-bd1972bc0b8a
    Have a look at the FM IDOC_XML_FROM_FILE. May be it helps...
    Regards

Maybe you are looking for

  • Shipment cost condition not copied in the billing document

    hi I have created shipment for the delivery and compelted the shipment cost as well , however when i create the billing document the shipment cost conditions are not copied in to the billing document. i have already set up pricing source as F in copy

  • Parameter dialog

    im working on a vb.net app in VS.net2005 with crystal reports XI. i would like to disable the parameter dialog if at all possible? if not i would like to be able to get the parameter dynamic values added in the report to show in the dialog..?

  • Plugin opening on 2nd monitor

    I have a 2nd monitor hooked up to my Macbook pro. I have the mixer on the 2nd monitor however whenever I open a plugin for the first time it always opens on the laptop screen, even though I open it from the mixer on the second monitor. Once I move th

  • Invoking ALBPM (Oracle BPM) using Webservice calls

    Hi, I am trying to invoke Oracle BPM processes using webservice dynamically using events. I am presently not able to find any samples in this regard. Could somebody help me figure out a way to invoke Oracle BPM process dynamically using events ? I wo

  • How Good is MBP 1.83 I just ordered mine

    Hi guys I just ordered my MBP 1.83. I just wont to know your impressions good and bad. Mine is going to be with me in a month I hope I ship time will improve as I dont know if I can wait that long. Thank you Pedja