Java.util.text.SimpleDateFormat.parse strange behavior

Wow !
if I parse "10/14/2002" I get "0/2/2003", that is, the month 14 is considered 12 (december) + 2 additional months and therefore february in the next year!!
any idea ?
Paolo Denti
=============================
public class Test {
public static void main(String[] args) {
java.util.Date testDate = null;
java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("dd-MM-yyyy");
try {
testDate = formatter.parse("10-14-2002");
catch (java.text.ParseException e) {
System.out.println("Data scassata: " + e.getMessage());
System.exit(1);
System.out.println(testDate.toString());
=================================
prints "Mon Feb 10 00:00:00 CET 2003"

Tryformatter.setLenient(false);if you do not want this behaviour.

Similar Messages

  • Java.util.DateFormat / SimpleDateFormat

    Hi to All,
    It would be kind to let me know how could i resolve this problem .
    The user enters an expiry date as MM/dd/yyyy i.e 07/14/2002.
    This date I would like to store in the database in the following format:
    MM/dd/yyyy i.e '07/14/02 3:41:31 PM'
    I am able to store '7/14/02' but not the hour,minute,second and AM/PM part. How can i do so ?
    I have done it in this way :-
    String sExpiryDate = "07/14/2003";
    DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
    /* tried adding 'hh:mm:ss' to the above line , but i got ParseException */
    java.util.Date dExpiryDate = formatter.parse(sExpiryDate);
    long lexp_date = dExpiryDate.getTime();
    java.util.Date dExpireDate = new java.util.Date(lexp_date);
    This sExpireDate when printed comes as " Mon Jul 14 00:00:00 BST 2003 "
    How could i also add hour, minute and seconds to this expiry date?
    Any response will be appreciated.
    Thanks
    Regards,
    John

    Check out the javadoc for SimpleDateFormat. It will show you the way you can get the fields your missing
    http://java.sun.com/j2se/1.4/docs/api/java/text/SimpleDateFormat.html

  • HOWTO improve java.text.SimpleDateFormat.parse() performace?!!

    I am using SimpleDateFormat to parse the dates. The dates I am parsing have the time zone in format "+0500". So I am using the "z" format to parse it.
    After doing some CPU profile tests, it turns out that I am spending 33% of my entire processing time in parsing the time zones!!! Which is obviously too much time. Is there a way to improve performance on the time zone parsing? I made sure that only one SimpleDateFormat object is created when my application is initialized and I only use the parse() method repeatedly - so that the initialization cost would remain minimum.
    Also are there any other implementations of java.text.DateFormat which will perform better?
    Any help greatly appreciated.
    Thanks,
    Yash

    Are you using "z" or "Z". Upper case is right one.

  • Java.text.SimpleDateFormat.parse()

    This method does too much than I expected, say:
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    Date d = sdf.parser("00/00/0000");The d would be 1999, Nov. 30.
    After hacked the source code and some testing, I found it will roll backward or forward to generate a date. So, 01/32/2000 would become Feb. 01 2000. But I don't think this is a good implementation, as I expect it could throw exceptions at runtime if the string is not a valid time sting. And it's very difficult to debug, since any digit could be parsed!
    I think you guys here know what's behind the scene and why it's implemented like this. Any idea? Do you agree that the parse method should throw an exception when the fields of a date string're out of range? Or am I missing something?
    Comments are welcomed, and duke dollars're ready for those good answers.

    change your code as follows at it will do what you expected in the first places:
    <code>
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    sdf.setLenient(false);
    Date d = sdf.parser("00/00/0000");
    </code>
    Spieler

  • SAP GUI for Java 7.10 rev 7 - strange behavior using mouse

    Hi,
      I use last revision of SAP GUI for Java 7.10 on linux and I've noticied that some mouse actions do not work as expected. I'll use describe an examples:
    (1)
    In rev.6 I simly push button on screen and move over text, text is marked and then I can use CTRL-C to copy text to clipboard.
    In rev.7 pushing button and move does nothing. I need one initial click more and then it works as expected.
    (2)
    Click to icon in an ABAP list sometimes activate another icon from screen (it seems that focus isn't moved from its previous position to new mouse cursor position).
    Because rev.7 has been released at the end of 2008, it is possible, that some dotted revision (solving these troubles) has been released, does anybody know solution?
    Thank you for some hints,
      Pavel

    Hello Pavel,
    we have not yet been aware of such issues, so a newer dotted version would likely not make a difference.
    (1) The behavior pretty much depends on the specific component you are clicking and selecting its text.
    So a specific test case identifying the component is required to investigate the issue.
    (2) Also for this case I ask to provide the exact context, even if it happens there only "sometimes".
    Please provide also information requested in [note 326558|https://service.sap.com/sap/support/notes/326558], parts 2.) and 3.)
    If you could provide all this as part of a [support message|http://service.sap.com/message] would be great.
    Best regards
    Rolf-Martin

  • Error in Parser.fx file "incompatible types found   : java.util.Properties"

    Hi,
    In parser file "Parser.fx",
    public-read def PROPERTIES_PARSER = StreamParser {
    override public function parse(input : java.io.InputStream) : RecordSet {
    var props = javafx.util.Properties {};
    props.load(input);
    input.close();
    MemoryRecordSet {
    records: [
    MapRecord {
    fields: props
    due to under line portion an error is appearing:
    "incompatible types
    found : javafx.util.Properties
    required: java.util.Map
    fields: props".
    Please suggest some solution.
    Thanks in advance.
    regards,
    Choudhary Nafees Ahmed
    Edited by: ChoudharyNafees on Jul 5, 2010 3:48 AM

    Parser.fx
    package org.netbeans.javafx.datasrc;
    import javafx.data.pull.PullParser;
    import javafx.data.pull.Event;
    import org.netbeans.javafx.datasrc.MemoryRecordSet;
    public-read def PROPERTIES_PARSER = StreamParser {
        override public function parse(input : java.io.InputStream) : RecordSet {
            var props =java.util.Properties{};
            props.load(input);
            input.close();
            MemoryRecordSet {
                records: [
                    MapRecord {
                        fields: props
    public-read def LINE_PARSER_FIELD_LINE = ".line";
    public-read def LINE_PARSER = StreamParser {
        override public function parse(input : java.io.Reader) : RecordSet {
            var line : String;
            var result : Record [] = [];
            line = readLine(input);
            // BEWARE  ("" == null) is true
            while (line != null or "".equals(line)) {
                var map = new java.util.HashMap();
                map.put(LINE_PARSER_FIELD_LINE, line);
                var record = MapRecord {
                    fields: map
                insert record into result;
                line = readLine(input);
            MemoryRecordSet {
                records: result
    function readLine(in : java.io.Reader) : String {
        var str = new java.lang.StringBuilder;
        while (true) {
            var c = in.read();
            if (c == -1) {
                return if (str.length() == 0) then null else str.toString();
            } else if (c == 0x0D) {
                c = in.read();
                if (c == 0x0A or c == -1) {
                    return str.toString();
                str.append(0x0D);
            } else if (c == 0x0A) {
                return str.toString();
            str.append(c as Character);
        str.toString()
    public-read def JSON_PARSER = StreamParser {
        function toSequence(list : java.util.List) : Record [] {
            var result : Record [] = [];
            var ii = list.iterator();
            while (ii.hasNext()) {
                var r = ii.next() as Record;
                insert r into result;
            result
        override public function parse(input : java.io.InputStream) : RecordSet {
            var topLevel : Object;
            def parser = PullParser {
                documentType: PullParser.JSON
                input: input
                var mapStack = new java.util.Stack();
                var currentMap : java.util.Map;
                var recordsStack = new java.util.Stack();
                var currentRecords : java.util.List;
                var lastEvent: Event;
                onEvent: function(event: Event) {
                    if (event.type == PullParser.TEXT) {
                        currentMap.put(event.name, event.text)
                    } else if (event.type == PullParser.INTEGER) {
                        currentMap.put(event.name, event.integerValue)
                    } else if (event.type == PullParser.NULL) {
                        currentMap.put(event.name, null)
                    } else if (event.type == PullParser.START_ELEMENT) {
                        if (lastEvent.type == PullParser.START_ARRAY_ELEMENT) return;
                        var oldMap = currentMap;
                        var temp = new java.util.HashMap();
                        temp.put(new Object(), null);
                        currentMap = temp;
                        currentMap.clear();
                        mapStack.push(currentMap);
                        if (topLevel == null) topLevel = currentMap;
                        if (oldMap != null) {
                            var mr = MapRecord {
                                fields: currentMap
                            if (event.name == "" and lastEvent.type == PullParser.START_VALUE) {
                                oldMap.put(lastEvent.name, mr)
                            } else {
                                oldMap.put(event.name, mr)
                    } else if (event.type == PullParser.START_ARRAY_ELEMENT) {
                        var temp = new java.util.HashMap();
                        temp.put(new Object(), null);
                        currentMap = temp;
                        currentMap.clear();
                        mapStack.push(currentMap);
                        var mr = MapRecord {
                            fields: currentMap
                        currentRecords.add(mr);
                    } else if (event.type == PullParser.END_ELEMENT) {
                        mapStack.pop();
                        if (not mapStack.empty()) {
                            currentMap = mapStack.peek() as java.util.HashMap;
                        } else {
                            currentMap = null;
                    } else if (event.type == PullParser.END_ARRAY_ELEMENT) {
                        if (lastEvent.type == PullParser.END_ELEMENT) return;
                        mapStack.pop();
                        if (not mapStack.empty()) {
                            currentMap = mapStack.peek() as java.util.HashMap;
                        } else {
                            currentMap = null;
                    } else if (event.type == PullParser.START_ARRAY) {
                        currentRecords = new java.util.ArrayList();
                        recordsStack.push(currentRecords);
                        if (topLevel == null) topLevel = currentRecords;
                    } else if (event.type == PullParser.END_ARRAY) {
                        var set = MemoryRecordSet {
                            records: toSequence(currentRecords)
                        currentMap.put(event.name, set);
                        recordsStack.pop();
                        if (not recordsStack.empty()) {
                            currentRecords = recordsStack.peek() as java.util.List;
                        } else {
                            currentRecords = null;
                    lastEvent = event;
            parser.parse();
            if (topLevel instanceof java.util.Map) {
                var mr = MapRecord {
                    fields: topLevel as java.util.Map
                MemoryRecordSet {
                   records: [mr]
            } else {
                // List
                var rs = MemoryRecordSet {
                    records: toSequence(topLevel as java.util.List)
                rs
            parser.parse();
            var mr = MapRecord {
                fields: topLevel as java.util.Map
            MemoryRecordSet {
               records: [mr]

  • Strange problem with SimpleDateFormat.parse method

    I got something strange with this method.
    String pattern = "yyyy/MM/dd";
    String mydate = "2007/00/10";
    SimpleDateFormat formatter = new SimpleDateFormat(pattern);
    Date newdate = formatter.parse(mydate);
    I get "2006/12/10"
    is this correct.

    dongyisu wrote:
    and there no exception get thrown outYes it does. I ran this:
    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    public class DateFormatTest
       public static final String DEFAULT_DATE_FORMAT = "yyyy/MM/dd";
       public static void main(String[] args)
          DateFormat formatter = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
          formatter.setLenient(false);
          for (int i = 0; i < args.length; ++i)
             try
                Date date = formatter.parse(args);
    System.out.println("input: " + args[i] + " date: " + date);
    catch (ParseException e)
    System.err.println(args[i] + " is not a valid date");
    and got this when I input "2007/00/10":
    com.intellij.rt.execution.application.AppMain DateFormatTest 2007/00/10
    2007/00/10 is not a valid date
    Process finished with exit code 0%

  • Java.text.SimpleDateFormat millisecond problem...

    When I run this code:
    java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat();
    formatter.applyLocalizedPattern("yyyy-MM-dd HH:mm:ss.000000");
    java.util.Date date1 = formatter.parse("2001-08-14 13:49:38.000000", new java.text.ParsePosition(0) );
    System.out.println("Date 1 = " + date1);
    formatter.applyLocalizedPattern("yyyy-MM-dd HH:mm:ss.SSS000");
    java.util.Date date2 = formatter.parse("2001-08-14 13:49:38.000000", new java.text.ParsePosition(0) );
    System.out.println("Date 2 = " + date2);
    The output is:
    Date 1 = Tue Aug 14 13:49:38 GMT+01:00 2001
    Date 2 = null
    The only difference is in the localized pattern, date 1 is generated where milliseconds aren't in the localized pattern, date 2 is generated where milliseconds are in the localized pattern.
    Why is date2 null????

    Hi! When you use the second pattern, it appears that "yyyy-MM-dd HH:mm:ss.SSS000" is not an acceptable pattern. However, "yyyy-MM-dd HH:mm:ss.SSS" works. I'd hazard a guess that when you specify milliseconds, only three places are allowed.
    If you used pattern #2 as you had specified originally, a java.text.ParseException is thrown. With the above modification, it works as expected.
    Hope this helps!
    Cheers!

  • Java.text.SimpleDateFormat  with zones

    Hi,
    I have a log file which has a date format as below:
    20091224060656.000000+060
    Wondering if java.text.SimpleDateFormat would be able to parse it properly.I was seeing this API and it didnot have any exact syntax for parsing this kind of date format.
    Please let me know.
    Regards
    Sayan

    sayanb wrote:
    Hi,
    Thank you for the response.The problem is this is one our client's log file which we are trying to parse using the java.text.SimpleDateFormat from our own java application.
    Hence not sure about +060. I guess the part after the . represent the zone , please correct me.But +060 not sure what this means and I dont think java.text.SimpleDateFormat has a way to parse this.
    Please let me know your comments.Uhm, you need to "tell" SimpleDateFormat what the format is, if you don't know how to interpret the format, how are you going to be able to configure SimpleDateFormat. Contact your "client" and make sure you understand the format, then look at the API docs for SimpleDateFormat and hammer out a pattern string for that format. (But I would assume that the "part after the dot" is second fragments (smaller than milliseconds but larger than nanoseconds, about half-way between, what the name for that is, I'm not sure), and that the part with the "plus" is the timezone, probably +060 is the same as +0600.) IOW, you will probably have to "preprocess" the string removing the last three digits before the "plus" and adding a 0 to the end, but that is only a guess.

  • Strange result of SimpleDateFormat.parse()

    Hi,
    I'm having trouble with the parse data function as it does not return the correct hour.
    Here is what I'm doing:
    Date nullDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse("1900-01-01T00:00:00-0000");I would now expect nullDate to be Mon Jan 01 00:00:00 CET 1900
    But instead, it is Mon Jan 01 00:09:21 CET 1900
    Personally I cannot think of a reason why the time is not 0.
    Any ideas?

    I don't see the problem you see. What version of Java on what OS and in what time zone?
    P.S. I would certainly set the time zone for the parser i.e.
           SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
            parser.setTimeZone(TimeZone.getTimeZone("UTC"));
            Date nullDate = parser.parse("1900-01-01T00:00:00-0000");
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
            System.out.println(formatter.format(nullDate));On my Ubuntu 10.04 using JDK 1.6.0_20 in London (currently GMT) time zone I get
    1900-01-01 00:00:00 GMT

  • Parsing xhtml using java.util.regex

    I am parsing an XHTML file using the java.util.regex package and I am perplexed at why the following doesn�t work.
    The lines I wish to match are either like this:
    <span class="someclass"><b>Some String.</b></span></td>
    or
    Some String.</td>
    The code I use to try to achieve this is:
    Pattern somePattern = Pattern.compile(".*(<span class=\"someclass\"><b>)?(.*)[.](</b></span>)?</td>.*");
    String s = null;
    while((s = br.readLine()) != null) {
    if(somePattern.matcher(s).matches()) {
    System.out.println("0:" + eventMatcher.group(0));
    System.out.println("1:" + eventMatcher.group(1));
    System.out.println("2:" + eventMatcher.group(2));
    System.out.println("3:" + eventMatcher.group(3));
    I expect to get as output
    0:<span class="someclass"><b>Some String.</b></span></td> 1:<span class="someclass"><b>
    2:Some String
    3:</b></span>
    or
    0:Some String.</td>
    1:null
    2:Some String
    3:null
    depending on which lines provide the match as mentioned above. Instead I get:
    0:<span class="someclass"><b>Some String.</b></span></td>
    1:null
    2:(empty string)
    3:</b></span>
    or
    0:Some String.</td>
    1:null
    2:(empty string)
    3:null
    Any ideas? Thanks in advance.

    Consider the terms of ".*(<span class=\"someclass\"><b>)?(.*)[.](</b></span>)?</td>.*"
    .* - greedily collect characters
    (<span class=\"someclass\"><b>)? - optionallly collect information taht will always be matched by the previous .* pattern so will be empty.
    (.*) - greedily collect characters that will also have been swallowed by the first .* so will be empty
    [.] - a single .
    (</b></span>)? - optionally collection
    </td> - must be there
    .* - collect the rest of the charcters in the line.
    Therefore in general groups 1 and 2 will be empty because the first .* will have collected the information you wanted to capture!
    You could just make the first .* non-greedy by using .*? but this may fail for other reasons.
    So, in general terms, what are you trying to extract?

  • Java.util.Formatter vs. java.text.MessageFormat

    Hi,
    Which formatter is faster java.text.MessageFormat or java.util.Formatter?
    At the moment I format all my strings with java.text.MessageFormat, however I want to speed-up the formatting of the strings that I log, so I though of using java.util.Formatter instead.
    Is there a benchmark that compares between those formatters?

    hanoch_y wrote:
    Why do you day those 2 doesn't do the same thing? They format messages using parameters the user passes.A 747 and a dump truck both do the same thing: move people and cargo from one place to another. But people have been known to express strong preferences for one or the other, depending on their circumstances. They usually have pretty good reasons for their choices.
    No I didn't used a profiler. It just an hunch.Never trust hunches, especially when it comes to performance questions. You'll end up making a fool of yourself every time.

  • Strange behavior when deleting text in an email.

    When composing emails I have noticed that if I make a mistake and delete some text it behaves strangely.  This only happens if the text deleted is at the end of the message.  On deleting the text I am then left with a small highlighted area (like when you have used your cursor to select an area).  If I then try to continue typing it types a few letters and then stops and the new letters typed just go over and over in the same cursor spot.  This is difficult to describe so i hope I have made sense but it is extremely frustrating and I was wondering if anyone else was having the same problem of if it is a known bug???  If anyone knows, please could they let me know :-)
    Thanks
    P.S. I'm on an iMac using 10.7.3

    Thanks for the info sanjapet.
    1) I just trashed the Preferences
    com.apple.mail.plist
    com.apple.mail.plist.lockfile
    2) then reboot. It is still misbehaving in texts in Apple Mail. For example i select a whole paragraph but only some words are highlighted. Here is a sample
    http://www.pixentral.com/show.php?pi...rYnikzXiYS5Ir0
    very annoying indeed.
    3) Now i go to Preferences and
    com.apple.mail.plist
    com.apple.mail.plist.lockfile
    are not there any more. I thought Apple Mail will restored them automatically. Isn't that right?
    Best,

  • Cannot convert from java.util.Date to java.sql.Date

    In the below code am trying to get the current date and 60 days prior date:
    Date  todayDate;
              Date  Sixtydaysprior;
              String DATE_FORMAT = "MM/dd/yy";
              DateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
             Calendar cal = Calendar.getInstance();
              todayDate = sdf.parse(sdf.format(cal.getTime()));
              cal.add(Calendar.DATE, -60);
             Sixtydaysprior = sdf.parse(sdf.format(cal.getTime()));I have imported following files:
    <%@page
         import="java.util.Calendar,
                   java.text.SimpleDateFormat,
                   java.text.ParseException,
                            java.util.*"
    %>Shows up following error msg:
    Type mismatch: cannot convert from java.util.Date to java.sql.Date
    Thanks.
    Edited by: MiltonDetroja on May 22, 2009 11:03 AM

    Shows up following error msg:
    Type mismatch: cannot convert from java.util.Date to java.sql.Date
    I don't think this exception is thrown from the portion of code you have shown. As clearly specified in exception message, you cannot cast an instance of java.util.Date to java.sql.Date. you will need to do something like this
    java.util.Date today = new java.util.Date();
    long t = today.getTime();
    java.sql.Date dt = new java.sql.Date(t);

  • A bug in java.util.Date module?

    When I try to execute this code:
    private java.util.Date getStringAsDate(String s) throws Exception {
         SimpleDateFormat fmt = new SimpleDateFormat("DD.MM.yyyy");
             return fmt.parse(s);
    java.util.Date one = getStringAsDate("8.6.2005"), two = getStringAsDate("8.7.2005");
    if (one.compareTo (two) ==0 )
       System.out.println("Equals!");
    else
       System.out.println("Not equals!");
    System.out.println(one);
    System.out.println(two);I get this result:
    Equals!
    Sat Jan 08 00:00:00 GMT+01:00 2005
    Sat Jan 08 00:00:00 GMT+01:00 2005
    My locales are Czech, time zone GMT+01. Thoughts?

    Thanks.
    I was looking for an error in months as they were
    incorrect...Look into the API and you should see why the month value is wrong for the pattern you wrote:
    http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.htmlThe hint is in the definition of 'D' versus 'd'.

Maybe you are looking for

  • Is there a way that I can order online and have it arrive at a set date and time?

    Hello there Apple community, I am looking at buying an iPod Touch 5 gen but I'm not sure if I will be at home when it arrives. Is there a way for me to set it to arrive at a time like 4:30 Tuesday? And also, does apple deliver on labour day? This Mon

  • Import FOC(Free of Charge) PO (Manufacturing) with claimable duties

    Dear SAP guru, We're currently on 4.6C and implementing a project for India. We have a scenario for Import FOC(Free of Charge) PO (Manufacturing) with claimable duties. Material price in Material Master = 10(Basic) + 5.00(Un claimable duties) + 3.00

  • Move indexes to a different tablespace

    What is the best and easiest method to move all indexes/constraints to a different tablespace. I have 2 tablespaces one for data and the other for the indexes. At present, I have all data and indexes all in one tablespace. I would like to separate th

  • Passing parameters - urgent please

    Dear friends, In my first.jsp file i am passsing a emailaddress to second.jsp thru url. second.jsp is receiving the emailaddress using request.getparameter. However i have somany parameters like email. and i have hide these parameters, in which the u

  • IPad has messages sitting in outbox

    Why and what caused selected messages not get sent via cloud emIl. I have 18 sitting in there  a little red circle & ! beside every message that was now sent. How come & how do I get these to send M