DateFormat.parse(String)

can anybody tell me why I don't get a SHORT format:
import java.util.*;
import java.text.*;
public class MyDate{
   public static void main(String[] args){
      Date date = makeDate("04/22/2003");
      System.out.println(date); // what i get looks more like FULL
    public static Date makeDate(String dateString){
       Date date = null;
       try {
          DateFormat fmt = DateFormat.getDateInstance(DateFormat.SHORT);
          date = fmt.parse(dateString);
      catch(ParseException e) {}
      return date;
}Thank you.

what I think is tripping you up is that a java.util.Date is not a String. It looks like you're thinking that you can format a java.util.Date object and somehow it is "11/23/2004" (or whatever) - but it's not - it's just a number. So, you have this String that you want to convert to a java.util.Date (which you correctly did with the parse method of the DateFormat class) but then you turn around and want to convert that java.util.Date to a String so you can put it into a List, so why not just put the original String into your List? Is it because you want to change the format? Fair enough, then you can use two DateFormat implementations, one to parse the incoming String to a Date, then the other to format the Date to the format you want. Or is it so you can do the sort chronologically? If that's the case, then you can write up a Comparator to do that, or you can store Dates in your list, sort them, and when it comes time to display this thing (if you ever do that) use a DateFormat implementation to convert those to a formatted String.
Make sense?

Similar Messages

  • Is is possible to allow multiple date format strings pass DateFormat.parse?

    I'm trying to use DateFormat.parse to validate a date in the 20/12/08 format. I would like to allow users to input 20-12-08 or 20 12 08.
    The code currently looks like this:
    formatter = DateFormat.getDateInstance(DateFormat.SMALL, US);It is currently throwing an exception if 10-12-08 is sent in where as 10/12/08 works just fine.
    Is there a alternate us locale that is more lenient?
    setLenient(true) didn't solve the problem for me. I think that would accept 32/12/08 not 10-12-08.
    I could parse the date string and replace - or ' ' with a /.. Is that best practice?
    What other options do I have? Could I use SimpleDateFormat somehow?
    Thanks for the input

    That just doesn't seem clean. It will work, but I would rather not have a valid application flow use an exception to get its job done.
    The application is also international, so many locales on one format is valid. The US user base seems to think they can type in the date however they want. So passed into the method is the locale, I would have to modify a lot of code to send in a list of valid locales.
    The best solution for me would be to have a locale that would allow - or ' ' or /. That way I still only have to make one call to df.parse and an exception produces an invalid date message. Is that possible?
    Thanks

  • DateFormat.parse

    Hi all,
    I am trying to parse some Strings into date objects, but i'm getting some strange output.
    The dates (Strings) that go into my program are:
    2005/3/08 09:12:38
    2005/3/10 17:29:57
    2005/3/11 15:39:59
    2005/3/23 13:30:03
    2005/3/23 13:32:49
    my code should take these strings, parse them into dates, add them to a List and sort the list. But the output i get is:
    Mon Aug 26 09:12:00 BST 2013
    Wed Aug 26 17:29:00 BST 2015
    Thu Aug 25 15:39:00 BST 2016
    Fri Aug 25 13:30:00 BST 2028
    Fri Aug 25 13:32:00 BST 2028
    as u can see - these are not the strings i entered originally. the code i am using is:
    public java.util.Date dateConverter(String dateString) throws Exception
    {     int intMonth = 99;
         String [] months = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
              String month = dateString.substring(4,7);
         for (int i = 0 ; i < 12 ; i++)
         {     if (months[i].equals(month))
              {     intMonth = i+1;
         dateString = dateString.substring(24,28) + "/" + intMonth + "/" + dateString.substring(8,10) + " " + dateString.substring(10,20);
         java.util.Date newDate = dateFormat.parse(dateString);
         return newDate;
    can anyone tell me whats missing from my code, and how i can get the correct output.
    thanks

    What happens if you do this? dateString = dateString.substring(24,28) + "/" + intMonth + "/" + dateString.substring(8,10) + " " + dateString.substring(10,20);
    java.util.Date newDate =dateFormat.parse(dateString);
    System.out.println("Parsing string " + dateString + " into date " + newDate);

  • DateFormat parse validation

    This didn't seem to show up first time so I'll try again.
    The docs and tutorials indicate that DateFormat.parse should thorw an error if an invalid date is provided. However, the following throws no error:
    SimpleDateFormat formatter_mmddyy = new SimpleDateFormat ("MM/dd/yy");
    Date theDate = formatter_mmddyy.parse("13/22/05");
    What is the correct way to validate dates?
    -- Frank

    Depending on how strict you want your validation to be you can either:
    a) leave it as is and let it adjust as it sees fit (rolling forward if you try something like you just did)
    b) Call setLenient(false) to make it not do that, but allow extraneous cahracters at the end (so Strings like "12/22/05yasureyoubetcha" still come out valid)
    c) use the version of parse that takes a ParsePosition and manually verify that the passed in ParsePosition does not indicate an error and shows that the whole String was consumed during parsing.
    That's my take on it anyway
    Good Luck
    Lee

  • DateFormat.parse() reads 12:00:00 as 00:00:00?

    Hi, i have a method, which uses DateFormat.parse() function, and i want to check whether a date and time input is valid. as you can see from the following code; i have defined the format as (dd-mm-yyyy at hh:mm:ss). the problem is, if i pass a string as (dd-mm-yyyy at 12:21:23), the method changes hour field to '00'. i.e., the line denoted as LINE N in the code prints out 'dd-mm-yyyy at 00:21:23'. i have tested other hours and they are all fine, 00 is interpreted as 00, 24 is 00 which is fine, but 12 is also parsed to 00.... any way to change this please?
    Many thanks!
    public boolean isValidDate(String dt)
            boolean isValid=false;
            DateFormat datef=new SimpleDateFormat("dd-MM-yyyy 'at' hh:mm:ss",Locale.UK);
            java.util.Date d = new java.util.Date();
            try{
                d=datef.parse(dt);
                //////////////////////  LINE N //////////////////////////////////////////
                System.out.println("is this right"+d.toString());
                /////////////////////  LINE N //////////////////////////////////////////
                int hr = d.getHours();
                System.out.println("This is the hour "+hr);
                if(hr<=18&&hr>=9)
                    isValid=true;
                    System.out.println("hour ok");
                else{System.out.println("hour not ok");}
            catch(ParseException pe)
                isValid=false;
            return isValid;       
        }

    use gregoriancalendar instead
    -->
    http://java.sun.com/j2se/1.4.2/docs/api/java/util/Greg
    orianCalendar.htmlTrue.
    @OP. You should never call getHours() on a date object, you should always use a Calendar.
    Kaj

  • DateFormat parsing problem

    Hi,
    A little limitation I have discovered in DateFormat.
    I'm using SimpleDateFormat, and I supply the format "HH:mm"
    I expect the DateFormat parsing to fail when calling parse() for Strings such as "12:13:13", since in the format there is no seconds-resolution.
    Instead, the parsing runs without exception and returns the time 12:13:00 (The seconds are truncated).
    Is thyere a way to make the DateFormat to fail and throw an exception in such a scenario?
    Thanks,
    Miki

    I doubt it. Also, if you enter an invalid date such as Dec 34 2004, it may (or may not) return an invalid date such as something like Aug 23 1834 rather than throw an exception. I think its best to pass the string to a validate format class that you custom write to check the format (such as xx:xx:xx), and also a validate date class (after passing the validate format) that you custom write to see if its a valid date (such as Dec 34, or if Feb 29, 2003 really is a leap year).
    Actually, I dont even use the classes such as DateFormat class directly in my code. Instead, I have a custom class with a host of static functions (containing DateFormat) to do all kinds of date/timestamp/string convertions to deal with dates. My code uses that class instead.

  • SimpleDateFormat: Parse String To Date

    Hi
    I'm trying to parse Date-String to Date. But the Date-String I want to parse is embedded in a Text like:
    Bla bla bla bla bla bla 2004-05-05 bla bla bla bla bla.
    So I tried the attached Class to solve the problem, but it didn't work.
    Any ideas?
    Thanks Bona
    public class Test {
    private static SimpleDateFormat dateFormat = new SimpleDateFormat();
    private String text;
    private Date date;
    public Test() {
    /ry {
    text = "Bla bla bla bla bla bla 2004-05-05 bla bla bla bla bla.";
    date = toDate(text, "yyyy-MM-dd");
    System.out.println("Datum: "+date);
    } catch (ParseException pe) {
    System.out.println(pe.getMessage());
    public static void main(String[] args) {
    Test test1 = new Test();
    public static Date toDate(String dateString, String dateFormatPattern)
    throws ParseException {
    Date date = null;
    dateFormat.applyPattern(dateFormatPattern);
    dateFormat.setLenient(true);
    date = dateFormat.parse(dateString);
    return date;
    }

    Well, you need to extract the date pattern from that String.
    You can use regular expressions to do that. See theRegex package for info on how to do that.
    BTW - AFAIK, lenient date parsing means, that the parser accepts stuff that matches the pattern, but contains illegal values like "2004-02-30" ...

  • Parsing String

    i have problem to parse string to document
    i have string like this str = "<root><data>1</data><data>2</data><root>";
    how to parse this string in docoment xml

    import java.io.*;
    import org.jdom.*;
    import org.jdom.input.*;
    import org.jdom.output.*;
    public class PrettyPrinter {
       public static void main(String[] args) {
            // Assume filename argument
            String filename = args[0];
            try {
                // Build the document with SAX and Xerces, no validation
                SAXBuilder builder = new SAXBuilder();
                // Create the document
                Document doc = builder.build(new File(filename));
                // Output the document, use standard formatter
                XMLOutputter fmt = new XMLOutputter();
                fmt.output(doc, System.out);
            } catch (Exception e) {
                e.printStackTrace();
    }The above code is taken directly from
    http://www.javaworld.com/javaworld/jw-05-2000/jw-0518-jdom-p2.html
    u don't have to use Factories, this is what is said in that excerpt, it is very easy to use, and it is said that 80 % of the xml work can be done with 20 % or less work using JDOM.
    n joy ....
    </ksenji>

  • How to parse string to date in j2me?

    How to parse string to date in j2me?
    Please help me.

    Hi..
    String dyStr = "20";
    String mtStr = "1";
    String yrStr = "1999";
    Calendar cal = Calendar.getIntstance();
    int dy = Integer.parseInt(dyStr);
    int mt = Integer.parseInt(mtStr);
    int yr = Integer.parseInt(yrStr);
    cal.set(Calendar.DATE, dy);
    cal.set(Calendar.MONTH, mt);
    cal.set(Calendar.YEAR, yr);
    OK?

  • How could i parse string and link its model with my files in eclipse project?

    How could i parse string and link its model with my files in eclipse project?, as i read that we dont have to use standalone mode while working with eclipse projects.
    Example of what i want to do:
    I have file1.dsl in my project which contains some statements but the declaration of these statements are not in another file, i need to put them only in my code

    Hi Stefan,
    I have eclipse project contains 2 files, file1.dsl and file2.dsl, you can see the contents of the files below.
    file1.dsl contains some statements as shown below and file2.dsl contains the declarations of the variables. (like in C++ or Java we have declarations and usage)
    At this step file1.dsl and file2.dsl will be parsed successfully without any errors.
    Lets imagine that we will delete this project and will create another one and the new project will contain only file1.dsl (which contains the usage)
    At this step this file (file1.dsl) will contains some errors after parsing it, because we are using variables without declarations.
    So what i need is to parse the content of file2.dsl directly without adding this file to the project.
    I need to add the content of file2.dsl directly as a string in the code and parse it. just like that ( "int a;int b;" )
    And link file1.dsl with the model generated after parsing my string
    file1.dsl
    a++;
    b++;
    file2.dsl
    int a;
    int b;
    Thanks

  • Trouble parsing string

    I need to parse strings in the format "City State
    Abbreviation Zipcode" (ie "Glenview, IL 60062") to seperate them as
    their own variables. Problem is that sometimes there is a comma
    after city, sometimes not, so I've resorted to REfind to seperate
    the string. Here's the snippet, "city" is the entire string I
    mentioned above. The problem is that the refind I use seems to be
    returning 0. I'm trying to find the two capital letters that
    designate the state abbeviation.
    <cfif city neq ''>
    <cfset crpos = refind("[:upper:][:upper:]",city) >
    <cfset zip = trim(right(city,len(city)-crpos))>
    <cfset citystate = trim(left(city,crpos)) >
    <cfset newpos = find("#chr(32)#",citystate) >
    <cfset state =
    trim(right(citystate,len(citystate)-newpos)) >
    <cfset actualcity =
    trim(left(citystate,len(citystate)-newPos)) >
    </cfif>

    I probably should mention some explaination about what the
    regular expression is doing:
    Note: Groups are RegExp statements surrounded by ()
    Group 1: Combination of Letters and Spaces (e.g. City Name)
    optional comma and (required) space
    Group 2: 2 Character upper case state code (State Code) (note
    - depending on your source, state codes may not always be upper
    case)
    (required) space
    Group 3: 5 digit string (e.g. Zip Code) (note - again,
    depending on your source, you may be getting 5 digit zip + 4 or
    even non-us zip codes that may involve alpha characters.)
    The replace function is using back references to refer to the
    text matched by group 1,2 and 3.

  • Split Function unable to parse string correctly

    Hi,
    I'm using split function to split string into multiple rows using comma "," as delimiter. In a string I have following values which are not parsed correctly as they have comma inside the values. 
    American Dawn, Inc.
    Battalian USA, Inc.
    Fria USA, Inc.
    Lazer, Inc.
    Mexilink Inc.
    Is there any other approach to fix this issue?
    Here is the split function Im using:
    CREATE Function [dbo].[fnSplit] (
    @List varchar(MAX), 
    @Delimiter char(1)
    Returns @Temp1 Table (
    ItemId int Identity(1, 1) NOT NULL PRIMARY KEY , 
    Item varchar(MAX) NULL 
    As 
    Begin 
    Declare @item varchar(MAX), 
    @iPos int 
    Set @Delimiter = ISNULL(@Delimiter, ';' ) 
    Set @List = RTrim(LTrim(@List)) 
    -- check for final delimiter 
    If Right( @List, 1 ) <> @Delimiter -- append final
    delimiter 
    Select @List = @List + @Delimiter -- get position of
    first element 
    Select @iPos = Charindex( @Delimiter, @List, 1 ) 
    While @iPos > 0 
    Begin 
    -- get item 
    Select @item = LTrim( RTrim( Substring( @List, 1, @iPos
    -1 ) ) ) 
    If @@ERROR <> 0 Break -- remove item form list 
    Select @List = Substring( @List, @iPos + 1, Len(@List)
    - @iPos + 1 ) 
    If @@ERROR <> 0 Break -- insert item 
    Insert @Temp1 Values( @item ) If @@ERROR <> 0 Break 
    -- get position pf next item 
    Select @iPos = Charindex( @Delimiter, @List, 1 ) 
    If @@ERROR <> 0 Break 
    End 
    Return 
    End
    Another user in this forum posted a split function that
    he wrote:
    CREATE FUNCTION dbo.splitter(@string VARCHAR(MAX), @delim CHAR(1))
    RETURNS @result TABLE (id INT IDENTITY, value VARCHAR(MAX))
    AS
    BEGIN
    WHILE CHARINDEX(@delim,@string) > 0
    BEGIN
    INSERT INTO @result (value) VALUES (LEFT(@string,CHARINDEX(@delim,@string)-1))
    SET @string = RIGHT(@string,LEN(@string)-CHARINDEX(@delim,@string))
    END
    INSERT INTO @result (value) VALUES (@string)
    RETURN
    END
    GO
    Both of them are unable to parse above values incorrectly.
    FYI:  String is made of values that are selected
    by user in SSRS report. I think SSRS when combine values , put comma "," between multiple values.
    Any help or guidance would be appreciated.
    ZK

    duplicate of
    https://social.msdn.microsoft.com/Forums/sqlserver/en-US/820ac53c-ce25-4cc7-b828-5875a21d459d/split-function-unable-to-parse-string-correctly-in-ssrs-report?forum=sqlreportingservices
    please dont cross post
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • Hi to parse String "x;y:z" in Core Java

    hi to parse String "x;y:z" in Core Java

    Deepak_A_L wrote:
    how do i parse a String "X;Y:Z" in java i.e the results of parsing the string
    String s = "X;Y:Z"
    in terms of ENGLISH LANGUAGE -->(X Semicolon Y Colon Z)
    should be the below o/p individual Strings.
    X
    Y
    Z
    how do i get the above output.????Split on a semi- or regular colon using String's split(String regex) method.

  • DateFormat parse method usage

    Hi all,
    I am using the following code to parse the date String object to Date Object -
    ======================================================================
    if(dateString == null || dateString.trim().equals(""))
    return null;
    DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.SHORT,
    Locale.getDefault());
    Date d = null;
    try
    dateFormatter.setLenient(false);
    d = dateFormatter.parse(dateString);
    catch(ParseException pe)
    e.printStackTrace();
    =================================================================
    This code works perfectly for all formats of String objects I give except for the format - "12/12/12/1" in which case it converts to following date object -
    "Wed Dec 12 00:00:00 IST 2012" although its an invalid date String.
    Please let me know how I could have correct validation done in such cases or if this is the right behavior for DateFormat class.
    Thanks in advance!!

    I'm not going to comment on how exactly the parse method does its business, but I can suggest you use a regex pattern to validate the input you will send the parse method.
    Here is some info from the CodeProject website on date validation(Note that this is aimed at .NET - but regex works the same in Java as it does in .NET [i think]):
    Dates: As with numbers, we need two validators: a key-press validator, and a completion validator. The key-press validator can be pretty simple, if we limit how our user enters the date. Let’s say that we want to validate for the U.S. date format mm/dd/yyyy. Here is a validator that will do that:
    ^([0-9]|/)*$
    The regex reads: “Match any string that contains a sequence of zero or more characters, where each character is either a digit or a slash.” This validator will give the user immediate feedback if they enter an invalid character, such as an ‘a’.
    Copy that regex to Regex Tester and give it a try. Note that the validation fails if the user enters dashes, instead of slashes, between the parts of the date. How could we increase the flexibility of our regex to accommodate dashes? Think about the question for a minute before moving on.
    All we need to do is add a dash to the alternates group:
    ^([0-9]|/|-)*$
    We could add other alternates to make the regex as flexible as it needs to be.
    The completion validator does a final check to determine whether the input matches a complete date pattern:
    ^[0-2]?[1-9](/|-)[0-3]?[0-9](/|-)[1-2][0-9][0-9][0-9]$
    The regex reads as follows: "Match any string that conforms to this pattern: The first character can be a 0, 1, or 2, and it may be omitted. The second character can be any number and is required. The next character can be a slash or a dash, and is required…” And so on. This regex differs from the ones we used before in that it specifies each character of the pattern—the pattern is more of a template than a formula.
    Note the first character of the regex: ‘[0-2]’. This character points out that we can limit allowable digits to less than the full set. We can also expand them; for example, ‘[0-9A-F]’ would allow any hexadecimal digit. In fact, we can use this structure, known as a character class, to specify any set of characters we want. For example, the character class ‘[A-Z]’ allows capital letters, and ‘[A-Za-z]’ allows upper or lower-case letters.
    Our date regex also points out some of the limitations of regex validation. Paste the date regex shown into Regex Tester and try out some dates. The regex does a pretty good job with run-of-the-mill dates, but it allows some patently invalid ones, such as ‘29/29/2006’, or ‘12/39/2006'. The regex is clearly not ‘bulletproof’.
    We could beef up the regular expression with additional features to catch these invalid dates, but it may be simpler to simply use a bit of .NET in the completion validator:
    bool isValid = DateTime.TryParse(dateString, out dummy);
    We gain the additional benefit that .NET will check the date for leap year validity, and so on. As always, the choice comes down to: What is simpler? What is faster? What is more easily understood? In my shop, we use a regex for the key-press validator, and DateTime.TryParse() for the completion validator.
    Oh - and there is another regex validator:
    ^[0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30)))$
    which matches the yyyy-mm-dd date format and also validates month and number of days in a month. Could be improved as currently all leap year dates (yyyy-02-29) will validate.
    Sorry if I couldn't be of more help...
    Edited by: JoKiLlSyA on Oct 9, 2008 11:22 PM

  • DateFormat parse problem

    Hello all,
    I'm trying to parse a simple date, using java version 1.4.12, but for some reason an exception is thrown. Here is the code:
    DateFormat format = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT);
    Date date = format.parse("Nov 4, 2003 8:14 PM");
    Can anyone help?
    Thanks

    I always use SimpleDateFormat. One thing might be that the parsing pattern returned for your default locale doesn't match your input String.

Maybe you are looking for