SimpleDateFormat parses wrong date successfully (lenient = false). Why?

Hi
I've got a problem validating date by SimpleDateFormat. Format "yyyy" successfully parses string like "2009-78" into date 01.01.2009. Can you please help me with it?
Here is my code:
SimpleDateFormat format = new SimpleDateFormat("yyyy");
format.setLenient(false);
String dateStr = "2009-78";
Date date;
try {
    date = format.parse(dateStr);
} catch (ParseException e) {
    date = null;
    e.printStackTrace();
System.out.println(String.format("String '%s' parsed to date %s", dateStr, date));Output:
String '2009-78' parsed to date Thu Jan 01 00:00:00 MSK 2009I need an exception to be thrown in such situation. How can I check where the string represents a correct date?
Thanks for your help.
Evgeny
Edited by: su.eug on Apr 13, 2009 12:56 AM

Read the comments in the API:
[http://java.sun.com/javase/6/docs/api/java/text/DateFormat.html#parse(java.lang.String)|http://java.sun.com/javase/6/docs/api/java/text/DateFormat.html#parse(java.lang.String)]
You could try the other overload of parse, if you want to test whether the whole String was used:
[http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html#parse(java.lang.String, java.text.ParsePosition)|http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html#parse(java.lang.String,%20java.text.ParsePosition)]
(Sorry--the second link doesn't go to the right place. There is a version of "parse" with two parameters, which you can use to determine if the whole String was used.)

Similar Messages

  • My calender is showin the wrong date on the screen why is that?

    my calender is showing the wrong date how can I fix that can anyone help me?

    try rebooting your phone
    hold the home and lock button until the apple appears then let go

  • SimpleDateFormat, exclude wrong dates

    Is there a way to exclude incorrect dates with a SimpleDateFormat? I mean, say for instance that you want to enter 31st of June, 2009. That should produce an error, because that date is not possible. However, for some reason, that date is converted to the 1st of July.
    What I can do is convert the text to a Date object, than convert it back to a String and compare it to the original value. If these are different, throw an error. However, I hope there's a better, more proper way of doing this. Any help would be appreciated :-).

    I am unaware of a something that would automatically throw an error if that happened....
    But, there are only 12 months, and most of them are either 30 or 31 days. (not much work)
    Im not going to write all the code for you, You need to figure most of it out...but you could do something like:
    if (  (day > 31) && (month == Jan || month ==Mar ||...))
    else if ((day > 30) .... ))
    ...just dont forget about Feburary, and leap years ars every 4 years (it may be more complicated i dont remember):
    bool leapyear = false;
    if (years % 4 == 0)
      leapyear = true;

  • SimpleDateFormat.parse accepts invalid date string

    SimpleDateFormat("dd/MM/yyyy").parse(...) accepts invalid input strings (e.g. "1.1.2gsd001") without raising an exception.
    Where I do a mistake?
    Example:
    import java.text.*;
    import java.util.*;
    public class Test {
    public static void main(String[] args) throws ParseException {
    String s = "1.1.2gsd001";
    SimpleDateFormat sdf = new SimpleDateFormat("d.M.yyyy");
    sdf.setLenient(false);
    Date d = sdf.parse(s);
    System.out.println(d);
    GregorianCalendar gc = new GregorianCalendar();
    gc.setTime(d);
    The result is: Sun Jan 01 00:00:00 CET 2
    Thanks for your help.

    Tahnks s lot.
    Final code is (and it workes well):
    import java.text.*;
    import java.util.*;
    public class Test {
      public static void main(String[] args) throws ParseException {
        ParsePosition pp = new ParsePosition(0);
        String s = "1.1.2001";
        SimpleDateFormat sdf = new SimpleDateFormat("d.M.yyyy");
        sdf.setLenient(false);
        Date d = sdf.parse(s, pp);
        if (pp.getIndex() != s.length())
          throw new ParseException(String.format("Unparseable date: %s", s), pp.getIndex());
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(d);
    }

  • Why do I get the wrong date on my photos and emails?

    All my photos in iphoto and emails are coming up with the wrong date. Why is this and how can I correct it?
    I have made sure that the computer's date and time are ok.

    You may want to re-post in the iPhoto forum if it only happens in iPhoto.

  • SimpleDateFormat gives the wrong date

    Hi
    I'm retreiving a java.sql.Date, and using a SimpleDateFormat("dd.MM.yyyy") to format it. For some reason, some of my users (located in other countries) end up with the wrong dates (it's an applet)and others don't. Any similar experiences/thoughts?

    Thanks for the info....I'm using 1.3, so that's unlikely to be it.
    I narrowed it down to a timezone problem difference problem between my applet and the server. Does anyone know how I can get an applet to behave like it's in a different timezone. Is there a single place I can set it (like maybe a System.setTimezone or something?). I don't want to go around messing with my Locales in every single Date or Calendar object I use. I just need my applets to think they're running in the same timezone as the server. Any similar experiences/quick fixes?

  • Why is CS4 putting wrong dates on files?

    Moved my CS4 from XP computer to new Windows7 computer. All seemed fine for a week.
    Now when I create or change a file, it does not put correct date on file (e.g., instead of 5/30/11 it will put 3/26/10 or on 6/2 it will show a date of 5/3/11 on the file). Wrong date shows in Explorer too but when I right click the file, the correct date is shown in properties. I can open the file in Adobe if I type in the filename.
    System date, clock, etc. are all fine.  No other program (Access, Word, Flash) does this
    Don't know if there's a connection but I did move over my preference/preset files from the XP just before this happens. I'd appreciate any help....thanks

    Aha!  Your Explorer view is displaying the Date Taken, which is of course the date the image was originally captured (and which is stored in the EXIF data within the file).
    That it is different from the Modification Date normally seen in Details view is because Explorer tries to show you a view of your files that can differ depending on the types of files it senses you have in the folder.  A real head-scratcher if you don't expect it.
    You can alter this behavior, on a folder by folder basis, by right-clicking the folder, choosing Properties, clicking the Customize tab, then choosing General Items.
    What many don't know is that you can set the behavior Windows-wide to ALWAYS show General Items views for all new folders (i.e., circumventing the derivation of what Customization to make by looking at the files) by this process, excerpted from my Windows 7 tuning guide.  Note that it involves adding an item to the registry with regedit - BE VERY CAREFUL WITH THIS:
    Configure Explorer
    Do not set Folder Types but use "General Items" for all by adding the following string value to the registry:
    [HKEY_CURRENT_USER\Software\Classes\Local Settings\
    Software\Microsoft\Windows\Shell\Bags\AllFolders\Shell]
    FolderType                           REG_SZ                NotSpecified
    -Noel

  • SimpleDateFormat parsing difficulty

    Hello all,
    Recently, I had to parse Strings into Dates using SimpleDateFormat. The difficulty I had was because the Strings had timezone offsets. The code below shows the 3 tests it took to create a Date object of specified TimeZone.
    Test 1
    Fails because I don't set the TimeZone for SimpleDateFormat.
    Test 2
    Works for the first String because the TimeZone matches the timezone in the String.
    Test 3
    Works for all Strings, but is cumbersome because I have to parse the end of the String myself.
    My question is this: Shouldn't SimpleDateFormat parse a String directly into a Date without having you to specify the TimeZone of that Date? This problem was very annoying to solve and goes against logic (at least mine!).
    I'm interested in any thoughts on this matter. Am I being unreasonable, or is this poorly explained in the API?
    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.SimpleTimeZone;
    public class DateTests {
         private static String DATE_FORMAT = "yyyyMMddHHmmss.SSSZ";
         private static String[] TEST_DATA = {
              "20020125120434.175+0800",
              "20031101195801.942+0000",
              "20041231000159.999-0536",
              "20050220165427.531-1100"
         private static int MINUTE = 60 * 1000; //in milliseconds
         private static int HOUR = 60 * MINUTE;
         public static void main(String[] args) {
              test1();
              test2();
              test3();
         private static void test1() {
              System.out.println("**** TEST 1 ****\n");
              DateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
              formatter.setLenient(false); //want to check that dates are valid
              for (String dateString : TEST_DATA) {
                   try {
                        Date date = formatter.parse(dateString);
                        System.out.println("Success! The date is: "+date.toString());
                   } catch (ParseException e) {
                        System.out.println(dateString + " has error index of: " + e.getErrorOffset());
              //out of curiousity, lets see the String representation of the current date & time
              Date now = new Date();
              String currentDate = formatter.format(now);
              System.out.println("\nThe current date as a String: "+currentDate);
              System.out.println("\n");
         private static void test2() {
              System.out.println("**** TEST 2 ****\n");
              DateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
              formatter.setLenient(false); //want to check that dates are valid
              //lets make the timezone +0800
              formatter.setTimeZone(new SimpleTimeZone(8 * HOUR, "GMT")); //8 hour offset
              for (String dateString : TEST_DATA) {
                   try {
                        Date date = formatter.parse(dateString);
                        System.out.println("Success! The date is: "+date.toString());
                   } catch (ParseException e) {
                        System.out.println(dateString + " has error index of: " + e.getErrorOffset());
              System.out.println("\nSuccess for the first date. Why? The timezone of the formatter matches the date.");
              System.out.println("\n");
         private static void test3() {
              System.out.println("**** TEST 3 ****\n");
              DateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
              formatter.setLenient(false); //want to check that dates are valid
              for (String dateString : TEST_DATA) {
                   try {
                        //lets set a timezone for each individual date
                        int length = dateString.length();
                        int gmtMinutes = Integer.parseInt(dateString.substring(length-2, length));
                        int gmtHours = Integer.parseInt(dateString.substring(length-4, length-2));
                        int timeZone = gmtMinutes * MINUTE + gmtHours * HOUR;
                        timeZone = dateString.charAt(length-5) == '+' ? timeZone : -timeZone;
                        formatter.setTimeZone(new SimpleTimeZone(timeZone, "GMT"));
                        Date date = formatter.parse(dateString);
                        System.out.println("Success! The date is: "+date.toString());
                   } catch (ParseException e) {
                        System.out.println(dateString + " has error index of: " + e.getErrorOffset());
    }-Muel

    Date objects don't have time zones.
    This is true, my problem was that I needed to parse both the Date and the TimeZone from a String. I got misled by the SimpleDateFormat documentation (the symbol Z), and somehow got the impression that a Date should have an associated TimeZone!
    In hindsight, it is clear that Z should be used for Date strings containing a timezone and that SimpleDateFormat uses the timezone to modify the Date so that it's correct for the timezone of the current machine. If that makes sense!
    -Muel

  • 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

  • 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

  • Problem with SimpleDateFormat.parse()

    Hello
    I have a problem with the parse-function in SimpleDateFormat.
    When i try to parse the date Fri Jul 15 17:23:41 2005 with this pattern EEE MMM d HH:mm:ss yyyy i get the exception java.text.ParseException: Unparseable date: "Fri Jul 15 17:23:41 2005".
    This is my code:
    SimpleDateFormat df=new SimpleDateFormat("EEE MMM d HH:mm:ss yyyy");
    try {
      df.parse(strDate);
    } catch (ParseException e) {
      e.printStackTrace();
    }Can someone explain me what i did wrong?
    Thanks
    Matthias

    Since your name is "Matthias" it is possible that your locale is one that does not use the English language. If that is the case then your problem is that "Fri" or "Jul" are not correct abbreviations in your language.
    Easiest way to test this idea is to format a date (such as now) using that SimpleDateFormat object and see what the output looks like.

  • Parsing a date string

    I need to parse a bunch of date strings in 'UTCG' format (whatever that really means).
    They all look like:
    1 Jan 2001 00:00:00.00
    I can't figure out which of the Java date formats parse this. I've tried many varients of:
    DateFormat.getTimeInstance(DateFormat.MEDIUM,Locale.GERMANY)
    without success.
    Help!!!!

    Here is a bit of info from the API doc - notice in the first paragraph it talks about the Date object, format seems similar. At the bottom of info is the Short, Long, etc, format tyoes, check those out... - Bart
    public abstract class DateFormat
    extends Format
    DateFormat is an abstract class for date/time formatting subclasses which formats and parses dates or time in a language-independent manner. The date/time formatting subclass, such as SimpleDateFormat, allows for formatting (i.e., date -> text), parsing (text -> date), and normalization. The date is represented as a Date object or as the milliseconds since January 1, 1970, 00:00:00 GMT.
    DateFormat provides many class methods for obtaining default date/time formatters based on the default or a given locale and a number of formatting styles. The formatting styles include FULL, LONG, MEDIUM, and SHORT. More detail and examples of using these styles are provided in the method descriptions.
    DateFormat helps you to format and parse dates for any locale. Your code can be completely independent of the locale conventions for months, days of the week, or even the calendar format: lunar vs. solar.
    To format a date for the current Locale, use one of the static factory methods:
    myString = DateFormat.getDateInstance().format(myDate);
    If you are formatting multiple dates, it is more efficient to get the format and use it multiple times so that the system doesn't have to fetch the information about the local language and country conventions multiple times.
    DateFormat df = DateFormat.getDateInstance();
    for (int i = 0; i < a.length; ++i) {
    output.println(df.format(myDate) + "; ");
    To format a date for a different Locale, specify it in the call to getDateInstance().
    DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE);
    You can use a DateFormat to parse also.
    myDate = df.parse(myString);
    Use getDateInstance to get the normal date format for that country. There are other static factory methods available. Use getTimeInstance to get the time format for that country. Use getDateTimeInstance to get a date and time format. You can pass in different options to these factory methods to control the length of the result; from SHORT to MEDIUM to LONG to FULL. The exact result depends on the locale, but generally:
    SHORT is completely numeric, such as 12.13.52 or 3:30pm
    MEDIUM is longer, such as Jan 12, 1952
    LONG is longer, such as January 12, 1952 or 3:30:32pm
    FULL is pretty completely specified, such as Tuesday, April 12, 1952 AD or 3:30:42pm PST.

  • SimpleDateFormat parse fails !!!

    Hi guys, has anyone have a solution to this problem:
      SimpleDateFormat fr = new SimpleDateFormat("dd-MM-yyyy");
        fr.setLenient(false);
        System.out.println(fr.parse("10-10-00"));-SimpleDateFormat seems not capable to parse 00 year when year is in four digit format.
    Is there any trick to parse this as a 2000 year as a simple way ???
    Thanks in advance

    I know if I use 2 digits the problem gets solved, I
    need to solve it because there are customers that
    need four digits in format, so I need to be able to
    parse in 4 digits 2000 year in a faster way
    It sounds like you're failing to distinguish between parsing and formatting. If you need to parse a four-digit year, then feed it a string with a four-digit year. You may need to use more than one DateFormat object; e.g., one for parsing, one for formatting.
    Formatting a Date Using a Custom Format
    Parsing a Date Using a Custom Format

  • SimpleDateFormat parsing problem

    Hi All,
    I am creating a date "12142007 14:30" by parsing this string with the SimpleDateFormat object. However, when I convert it back to string and ask it to spit it out it gives me a completely different date of "Sun Jun 14 14:00:00 CDT 2009".
    Am I missing something here ? Not sure if i have to put something in the parse position. Any help would be appreciated.
    Thanks and Regards,
    *public void test2() throws Exception{*
    *          SimpleDateFormat sdf3 = new SimpleDateFormat("MMddyyyy HH:MM");*
    *          Date theDate = sdf3.parse("12142007 14:30");*
    *          System.out.println(theDate.toString());          *
    Edited by: mikematic_wha on Dec 14, 2007 9:42 AM

    PeterBro wrote:
    Try that again with the spelling corrected
    public void Calest()
              String tempDate = textField2.getText(); // ie 20080128
              SimpleDateFormat ofd = new SimpleDateFormat("yyyyMMdd");
         Date tod = odf.parse(tempDate); // this line errors
         }Peter,
    Why don't you return to the thread you started where you got a couple of answers and if you have a follow up question post it there.
    [http://forum.java.sun.com/thread.jspa?threadID=5290540]

  • How can I get my @mac email to work? when I try to reset password, i cannot access email for this and the security tells me I have wrong date of birth

    Have used bilmac@mac email address for years last couple of weeks am getting message icloud needs password which it then rejects, when I try to reset password,they want email to verify i cannot access email and the security question is D. O B. it tells me I have wrong date of birth. so I am stumped, any ideas bilmac

    COME ON PEOPLE. (WHY ARE THE LETTERS SO BIG HERE?) I AM VERY OLD AND JUST LIKE THINGS TO STAY THE SAME. I DID NOT, DO NOT, WANT ICLOUD TO DO ANYTHING I HAVE NOT USED IT AT ALL YET IT HAS MANAGED TO MESS UP MY EMAIL ADDRESS WHICH I HAVE BEEN USING FOR YEARS, IT ASKS FOR PASSWORD THEN REJECTS AND WHEN I TRY TO RESET WITH APPLE ID THEY ASK FOR SECURITY AS I CANNOT ACCESS THE EMAIL ADDRESS THEY HAVE FOR ME BECAUSE ICLOUD ASKS FOR PASSWORD, THEN APPLE TELL ME I DONT KNOW MY OWN DATE OF BIRTH, VERY CONFUSING

Maybe you are looking for

  • Adobe photoshop cs2-cs3 cheap!!!!!!

    I am student in UK I am enjoying new macbook What i need now is adobe photoshop cs2 or cs3 as cheap as possible Do you no anyplace where i can get this program as very cheap legally Thanks for any answers

  • How to backup my itunes library to my time capsule automatically?

    so that i can wire my time capsule to my linn sneaky dsm hifi using network cable? because connecting my hifi using Airport express doesn´t always work. Maybe because all has to run over my mac?

  • Sound not coming out for right headphone

    If I press the headphone jack backwards, I can get sound coming out of both earpieces. However, if I just let it stand still, I can only hear it coming out of the left side. I tried different headphones, so it's the iPod and not the headphones. My wa

  • Are third party disk utilities really necessary?

    Are third party disk utilities [such as TechTool Pro or Disk Warrior] really necessary on a G5? Does the Apple Disk Utility perform all necessary repair functions?

  • Binding a imac to MacMini Server

    Hello, I am having an issue with binding an iMac to my OpenDirectory domain. To give you a background of my environment. I have AT&T uverse. The Server is connected to the AT&T gateway via wired ethernet. The iMac is connected via Wireless connection