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

Similar Messages

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

  • 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

  • RE: (forte-users) XML Parser - Reading an XML document intothe Document

    Hi Laks
    Here is an example of converting a XML doc to a DOM object.
    The method is ParseXML(pXMLString:TextData, pListType:CSAListInterface).
    Hope this helps.
    Argyris Simakis
    Corporate Services Applications ITB
    Sydney AUSTRALIA
    -----Original Message-----
    From: Narayanan, Lakshmi [mailto:lnarayanoxhp.com]
    Sent: Thursday, April 06, 2000 8:31 AM
    To: 'kamranaminyahoo.com'
    Subject: (forte-users) XML Parser - Reading an XML document into the
    Document Object
    Importance: High
    Hi guys,
    I have been trying to read an XML file and feed it into the XMLParser.
    I have read about the DOM API, and i can work with the DOM API in java
    scripts. How
    will i play with it in TOOL implementation of DOM API. Can anyone guide me
    in this
    process.
    Thanks for your help.
    Laks
    For the archives, go to: http://lists.xpedior.com/forte-users and use
    the login: forte and the password: archive. To unsubscribe, send in a new
    email the word: 'Unsubscribe' to: forte-users-requestlists.xpedior.com

    Hi Laks
    Here is an example of converting a XML doc to a DOM object.
    The method is ParseXML(pXMLString:TextData, pListType:CSAListInterface).
    Hope this helps.
    Argyris Simakis
    Corporate Services Applications ITB
    Sydney AUSTRALIA
    -----Original Message-----
    From: Narayanan, Lakshmi [mailto:lnarayanoxhp.com]
    Sent: Thursday, April 06, 2000 8:31 AM
    To: 'kamranaminyahoo.com'
    Subject: (forte-users) XML Parser - Reading an XML document into the
    Document Object
    Importance: High
    Hi guys,
    I have been trying to read an XML file and feed it into the XMLParser.
    I have read about the DOM API, and i can work with the DOM API in java
    scripts. How
    will i play with it in TOOL implementation of DOM API. Can anyone guide me
    in this
    process.
    Thanks for your help.
    Laks
    For the archives, go to: http://lists.xpedior.com/forte-users and use
    the login: forte and the password: archive. To unsubscribe, send in a new
    email the word: 'Unsubscribe' to: forte-users-requestlists.xpedior.com

  • RE: (forte-users) XML Parser - Reading an XML document intothe D ocumen

    Hi Simakis,
    Your attachments explained the exact start i was looking for.
    Thanks a lot for sharing.
    Thanks
    Laks
    -----Original Message-----
    From: Simakis, Argyris [mailto:Argyris.Simakisdet.nsw.edu.au]
    Sent: Thursday, April 06, 2000 12:35 AM
    To: 'Narayanan, Lakshmi'
    Cc: 'kamranaminyahoo.com'
    Subject: RE: (forte-users) XML Parser - Reading an XML document into the
    D ocument Object
    Hi Laks
    Here is an example of converting a XML doc to a DOM object.
    The method is ParseXML(pXMLString:TextData, pListType:CSAListInterface).
    Hope this helps.
    Argyris Simakis
    Corporate Services Applications ITB
    Sydney AUSTRALIA
    -----Original Message-----
    From: Narayanan, Lakshmi [mailto:lnarayanoxhp.com]
    Sent: Thursday, April 06, 2000 8:31 AM
    To: 'kamranaminyahoo.com'
    Subject: (forte-users) XML Parser - Reading an XML document into the
    Document Object
    Importance: High
    Hi guys,
    I have been trying to read an XML file and feed it into the XMLParser.
    I have read about the DOM API, and i can work with the DOM API in java
    scripts. How
    will i play with it in TOOL implementation of DOM API. Can anyone guide me
    in this
    process.
    Thanks for your help.
    Laks
    For the archives, go to: http://lists.xpedior.com/forte-users and use
    the login: forte and the password: archive. To unsubscribe, send in a new
    email the word: 'Unsubscribe' to: forte-users-requestlists.xpedior.com

    Hi Simakis,
    Your attachments explained the exact start i was looking for.
    Thanks a lot for sharing.
    Thanks
    Laks
    -----Original Message-----
    From: Simakis, Argyris [mailto:Argyris.Simakisdet.nsw.edu.au]
    Sent: Thursday, April 06, 2000 12:35 AM
    To: 'Narayanan, Lakshmi'
    Cc: 'kamranaminyahoo.com'
    Subject: RE: (forte-users) XML Parser - Reading an XML document into the
    D ocument Object
    Hi Laks
    Here is an example of converting a XML doc to a DOM object.
    The method is ParseXML(pXMLString:TextData, pListType:CSAListInterface).
    Hope this helps.
    Argyris Simakis
    Corporate Services Applications ITB
    Sydney AUSTRALIA
    -----Original Message-----
    From: Narayanan, Lakshmi [mailto:lnarayanoxhp.com]
    Sent: Thursday, April 06, 2000 8:31 AM
    To: 'kamranaminyahoo.com'
    Subject: (forte-users) XML Parser - Reading an XML document into the
    Document Object
    Importance: High
    Hi guys,
    I have been trying to read an XML file and feed it into the XMLParser.
    I have read about the DOM API, and i can work with the DOM API in java
    scripts. How
    will i play with it in TOOL implementation of DOM API. Can anyone guide me
    in this
    process.
    Thanks for your help.
    Laks
    For the archives, go to: http://lists.xpedior.com/forte-users and use
    the login: forte and the password: archive. To unsubscribe, send in a new
    email the word: 'Unsubscribe' to: forte-users-requestlists.xpedior.com

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

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

  • Parse/read complex data types in WSDLs

    i need to read the WSDL and identify the Ports, Operation, Bindings and types.
    My intention is to compare 2 WSDLS and also to create a UI client for web Service based on the WSDLs.
    My issue here is the WSDL contains Complex Data Type,i couldnt find classes that cud help me to read the complex/custom data types.
    A portion of wsdl is given below.
    <definitions ..>
    <types>
    <xsd:schema ....">
    <xsd:annotation>..
    </xsd:annotation>
    <xsd:complexType name="Address">
    <xsd:sequence>
    <xsd:element name="Address" maxOccurs="unbounded" minOccurs="0" type="xsdLocal:Address"></xsd:element>
    </xsd:sequence>
    </xsd:complexType>
    <xsd:complexType name="Name"><xsd:sequence>
    <xsd:element name="LastUpdated" maxOccurs="1" minOccurs="0" type="xsd:string"></xsd:element>
    <xsd:element name="House No" maxOccurs="1" minOccurs="0" type="xsdLocal1:string15"></xsd:element>
    <xsd:element name="City" maxOccurs="1" minOccurs="0" type="xsdLocal1:string30"></xsd:element>
    </definitions>{code}
    I got the Operations in the WSDLs as shown below.
    The input parameters are not direct parameters , they as nested/complex data types which i couldnt find a way to read..
    {code}
    protected void assertPortTypes(Definition definition) {
             Map portTypes = definition.getPortTypes();
             for (Object p : portTypes.values()) {
               PortType portType = (PortType) p;         
               String portTypeName = portType.getQName().getLocalPart();
               System.out.println("portTypeName\t"+portTypeName);
                  for (Object o : portType.getOperations()) {
                   Operation operation = (Operation) o;
                   String operationName = operation.getName();
                      System.out.println("operationName\t"+operationName);
    {code}
    Could any one please tell me if it is possible to parse the WSDL to read the Complex data types using java-wsdl classes
    Kindly give me the approaches that i could take here...
    thanks
    vyas                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    No, I am not using the AAL functions, but I was relying on the C99 support of clang and this document. The title of this document suggests that these extensions should also be available in CVI2015, CVI2017...

  • Problem with DateFormat.parse

    hi,
    I'm working using Java 1.5.
    i'm using SimpleDateFormat to parse date strings. My program has the following piece of code:
    Class DateConverter {
    SimpleDateFormat m_sdate = null ;
    public DateConverter() {
    this.m_sdate = new SimpleDateFormat("yyyyMMdd") ;
    public Date to_date(String dstr) {
    return this.m_sdate.parse(dstr) ;
    The date parsing works fine as long as I give dates upto "00010101" but throws java.text.ParseException for the value "00001231". I was just eager to know whether 00010101 is the least date that can be parsed???
    Thanks,
    Venkatesh

    I don't get a ParseException with your code; if there is an earliest date that can be parsed it's not 1/1/1.fmt = new SimpleDateFormat("yyyy/MM/dd");
    new SimpleDateFormat("dd.MM.y G").format(fmt.parse("0/12/31"));
    output: <31.12.01 BC>

  • How to parse reader comments in new source comment sections

    I enjoy reading through the comment sections to articles in various news sources.   However, the good comments are often hidden in the over abundance of spam and mind-numbing commentary.  I would like to write an application that will selectively
    extract certain comments that I feel will most likely offer informative content (i.e. to reduce the time and my effort to find comments worth reading).   For example, mind-numbing comments which I wish to ignore general consist of single sentences
    and it is not unusual for a comment section to have hundreds if not thousands of them.  Conversely, many informative comments are much longer in length (e.g. two or more paragraphs). 
    I am proficient in developing desk top applications in a rich client environment but have only minimal experience working with web-related applications.   As such, I am looking for suggestions on how I should approach this small project and work
    through it.
    1) Is anyone aware of existing projects or sample source code which parses the contents of web pages using .NET?
    2) It is possible to view the source of a browser web page.  For example, in IE10 I from the main menu [View][Source].   The source includes the text of the article but none of the comments.  That is, the actual comments are not
    included in the rendered HTML (e.g. view the source for
    http://www.cbc.ca/news/business/target-s-launch-into-canada-a-multifaceted-failure-1.2901789).   So how can I obtain the comments so that I can then filter the ones I wish to review and ignore all the others.
    If I should be posting this request in another forum then please let me know.
    ThanX
    Ian

    See the webpage below.  The DownLoadFile method or the method I posted at the end will get entire webpage.
    https://social.msdn.microsoft.com/Forums/vstudio/en-US/a75fb1e0-75a5-42eb-ad26-6d461eb94c69/why-my-calculation-using-while-and-substring-to-extract-string-from-text-is-not-extracting-the-right?forum=csharpgeneral#c743616a-ef72-4dd2-a22a-9c8c40ec784b
    jdweng

  • XML Parser - Reading an XML document into the DocumentObject

    Hi guys,
    I have been trying to read an XML file and feed it into the XMLParser.
    I have read about the DOM API, and i can work with the DOM API in java
    scripts. How
    will i play with it in TOOL implementation of DOM API. Can anyone guide me
    in this
    process.
    Thanks for your help.
    Laks

    Sorry for this post, here ist the complete text.
    Is it possible to create a XML Parser (javax.xml.parsers.SaxParser or javax.xml.parsers.DocumentBuilder) which reads from a ByteChannel?
    Example:
    java.nio.channels.FileChannel fc = new ...;
    javax.xml.parsers.SaxParser parser = ...;
    org.xml.sax.HandlerBase hb = ...;
    parser.parse( fc, hb );

  • How to interpret ( parse / read ) the Servlet Response contents ...

    I want to parse the response content before it is displayed in the browser. I wrote a Servlet Filter to parse the request / response.
    Since there are no public API s available to get the content of response, I am not sure , how to read the response.
    Any idea ??

    Implement HttpServletResponseWrapper, override the writing methods to let them write to some reuseable/accessible buffer and access it afterwards.

Maybe you are looking for