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

Similar Messages

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

  • 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);

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

  • Converting from spreadshet string to array and then back to spreadsheet string

    My questions is; why is the Spreadsheet string to array function creating more data than the original string had when you change the array back into a spreadsheet string. Im trying to analyze a comma delimited file using array functions since my column and row size is constant, but my data varies. Thus my reason for not using string parsing functions which would get more involved and difficult. So, however, after i convert to a 2D array of data from the comma delimited file I read from, and then I convert back to string using the Array to Spreadsheet String, I get added columns to the file, which prevents another program from receiving these files. Also, the data which I am reading is not all contiguous, it has gaps in some places for empty data. Looking at the file compared to the original after it has gone from string to array and then back to string again, looks almost identical except for the file size which got larger by 400 bytes and where the original file has empty spaces, the new file has a lot of commas added. Any idea?
    Charles

    The result you get is normal when the spreadsheet string contains rows of uneven length. Since the array rows have the same number of elements, nil values are added during the coonversion. And of course, the back to string conversion keep those added values in the string, with the associated commas.
    example : 3 x 3 array
    1,2,3
    4
    5,6,7
    is converted into
    1 2 3
    4 0 0
    5 6 7
    then back to
    1,2,3
    4,0,0
    5,6,7
    Chilly Charly    (aka CC)
             E-List Master - Kudos glutton - Press the yellow button on the left...        

  • 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

  • How to convert a String to an array

    Can somebody tell me how to convert a String to an array

    ronisto wrote:
    Can somebody tell me how to convert a String to an arrayI assume you mean to convert it into an array of the individual characters that comprise the String.
    Can you not simply look at the API documentation? Nothing in the String API jumps out at you?
    http://java.sun.com/javase/6/docs/api/index.html

  • I forgot the passcode to turn off restrictions. I have restored my iPad back to the factory settings and then synced it with the latest backup. The restrictions are still on and it is asking for the passcode. Can someone tell me how to get that off.

    I forgot the passcode to turn off restrictions. I have restored my iPad back to the factory settings and then synced it with the latest backup. The restrictions are still on and it is asking for the passcode. Can someone tell me how to get that off.

    The only option is to wipe the device clean and restore it to factory settings.  Hope you have a backup.
    Follow the instructions in  iOS: How to back up your data and set up your device as a new device http://support.apple.com/kb/HT4137 to restore the device to factory settings.
    Once you have setup the device as a new one, you can then sync it back with your iTunes account and all your music, apps, contacts and any other content sync'ed with iTunes will be loaded on the device. Any content that is stored only on the device and not sync'ed with iTunes, like app logins or data, will be lost during this process. Be forewarned that this is a long process and can take a couple of hours or more to complete. This can be painful, but it is necessarily so to prevent users from working around the security settings. After the restore is complete, you can setup a new Restrictions passcode. Make a note of the passcode to avoid this situation in future.
     Cheers, Tom

  • Easy Question! How Do I Play ONLY the Selection, and then playback stops?

    How Do I Play ONLY the Selection, and then playback stops? (Same as subject..)
    Thanks! I'm loving STP so far. I came from Sony Sound Forge so it's been difficult finding something that can compare, but I think I have it now! Lot's of advantages for STP too.

    I think you're confusing the audio loops with MIDI loops. The blue loops are audio loops which will play only on audio tracks. You can't 'play' those with a keyboard because they are actual audio files. The green loops contain MIDI data that corresponds with a software instrument, and if you drop them onto a Software Instrument track, they will open that instrument which you CAN play with an external keyboard or the caps lock keyboard.
    I might be missing some loops, but when I searched for Bell Tower I found only one, and it is a blue loop. So it can only be played as an audio loop on an audio track. However, if it were a green loop, you would NOT drop it on an external MIDI track (I think that's what you're trying to do if you're dragging it onto the 'Grand Piano MIDI instrument'), but you would create a SOFTWARE INSTRUMENT track, and drag it on that. Any internal sounds you want to play from Logic's instrument you'll do from Software Instrument tracks, and not MIDI tracks.
    What you should do to find a good chime sound that you can play with the caps lock keyboard is to create a Software Instrument Track, open the Library tab, and search there for a good chime. This will search all of the instruments and presets that Logic has for all of its internal instruments. Try 'Tubular Bells' and see if that works for you.
    If you need to use the bells from that loop, do what SC suggested, and take the hits from the audio file and load them into a sampler. Then you can play them the way you want to. If you don't know how to make a sampler, it's a bit complicated. Look up EXS24 in the manual, or check out
    http://www.youtube.com/user/SFLogicNinja
    I think he has a video or two on EXS24

Maybe you are looking for

  • Burning DVD from disc image

    I've been burning DVD's from disc images using Encore 1.0 for some time now. ever since I upgraded to 2.0, Encore gives me error messages on my project like: "first play not set" and "remote control problem". I don't see how these messages can appear

  • Problem of opening PDF files on the web

    I have installed the latest version of Acrobat Reader, but I still couldn't read some PDF files on the web, what should i do?

  • Add new TAB in ML81N Tcode..

    Hi Experts, I am new for screen exits... Can any one tell me how to add new tab in ML81N tcode in detail... Please waiting for your great answers... Thanks in advance, Kruthik Moderator message: please search for available information/documentation.

  • Do I need to do authority check for Logical Database?

    Hi, Just to check, do I need to code authority check into a Logical Database or Logical Database will do the check by itself without me coding? This is because I have a user which does not have rights to infotypes 2000 and above and the logical datab

  • Having issues with certain fonts in iWeb

    this has been an ongoing issue, and it seems to always be the same font. HelveticaCyrA-Bold HelveticaCyrA-BoldInclined HelveticaCyrA-Inclined HelveticaCyrA-Upright HelveticaInseratCyrA-Upright I do not have an original because i do not how these font