SimpleDateFormat Question

Hiii...
I am using SimpleDateFormat to do date validation and parsing. The problem that I am having is that I am setting the pattern of SimpleDateFormat to "MMddyyyy". Now, because of some implicit year validation, dates such as "121203" are taken as valid dates. I need to force the user to enter dates in (mmddyyyy) format.
Is their any function which would force the SimpleDateFormat function to throw a parse exception for the above type (mmddyyyy) of dates.
sanjay.

hii..
setLenient doesn't solve the problem. For instance the below code block doesn't throw any exception..
java.text.SimpleDateFormat dft = new java.text.SimpleDateFormat();
dft.applyPattern("MMddyyyy");
dft.setLenient(false);
java.util.Date dtObj = dft.parse("080103");
System.out.println(dtObj.toString());
Also, from what I have read..if setLenient is true then dates like 02302003(feb. 30th) is interpreted as Mar'2nd 2003. but by setting it to false feb.30th throws a parseException BUT it doesn't solve my problem of strict formatting.
sanjay.

Similar Messages

  • Few questions about Calendar / SimpleDateFormat classes

    Hi.
    I have few questions about Calendar class:
    1. How can I get only date representation (without the time)?
    after doing:
    Calendar cal = Calendar.getInstance();
    I tried to clear unecessary fields:
    cal.clear(Calendar.SECOND);
    cal.clear(Calendar.MINUTE);
    cal.clear(Calendar.HOUR_OF_DAY);
    But after printing the time, it seems that the HOUR was not cleared:
    SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    System.out.println(sdf1.format(cal.getTime()));
    ---> 03/11/2004 17:00:00
    Am I missing somthing?
    2. I want to make sure that two different formats couldn't be compared. i.e., if I'll try to parse one String according to different format -- ParseException will be thrown.
    String date = "19/04/2004 13:06:10";
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Date dateObj = sdf.parse(date);
    However, even though that formats are different, no exception is thrown and the return Date is 19/04/2004 00:00:00.
    How can I cause to exception to be thrown if formats are not identical?
    Thanks in advanced

    The Calendar class has a few of what Microsoft would call 'features'. :^)
    To clear the time, call:
    calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY), 0, 0, 0);
    If you want 'pessimistic' rather than 'optimistic' date parsing, you have two options:
    1) Call calendar.setLenient(false);
    See if that is strict enough for your needs, otherwise:
    2) Write code to ensure a stricter parsing of the string passed in. For example, you could very simply check the length of the string to determine if time data is also present.
    When parsing, a string like '02/29/02' would parse to the date '03/01/02'. Setting lenient to false may fix this, but the surest way is to do some testing and then make the parsing more pessimistic where it suits your needs.
    - Saish
    "My karma ran over your dogma." - Anon

  • SimpleDateFormat Easy Question..

    I can't get SimpleDateFormat to work, I get this exception:
    Unparseable date: "Sat Jun 15 20:23:23 CDT 2002"
    Here's the code:
    System.out.println(new SimpleDateFormat("yyyy-MM-dd").parse(new java.util.Date().toString()));What's wrong? When I was looking through the forum for help on this topic I also saw some weird things. Why does the parse() method of SimpleDateFormat work without a pos parameter, as defined in the API? Moreover, I saw some people passing a Date object instead of a String to the parse function. Am I missing something? Also, is there a better or easier way to format a Date like this? Thank you.

    Here you go:
    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.
    You can also set the time zone on the format if you wish. If you want even more control over the format or parsing, (or want to give your users more control), you can try casting the DateFormat you get from the factory methods to a SimpleDateFormat. This will work for the majority of countries; just remember to put it in a try block in case you encounter an unusual one.
    You can also use forms of the parse and format methods with ParsePosition and FieldPosition to allow you to
    progressively parse through pieces of a string.
    align any particular field, or find out where it is for selection on the screen.
    Hope this helps - Bart

  • Question about SimpleDateFormat

    Hi,
    I have a period of time in milliseconds that I would like to display in hh:mm:ss:SSS format.
    For some reason when I run the code below it always displays wrong. It should print out "00:01:00:000" but it always prints out "10:01:00:000". Could anyone tell me why it adds 10 hours to my value of 60000 milliseconds?
    public void testDateFormat()
    try
    long diff = 60000;
    SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss:SSS");
    System.out.println("Date: " + formatter.format(new Date(diff)));
    catch (Exception e)
    System.out.println("Error: " + e.getMessage());
    e.printStackTrace();
    Regards,
    Lachlan James

    Don't worry I found another way...
    long diff = 60000;
    millisecondsToString(diff);
    public static String millisecondsToString(long time)
    int milliseconds = (int) (time % 1000);
    int seconds = (int) ( (time / 1000) % 60);
    int minutes = (int) ( (time / 60000) % 60);
    int hours = (int) ( (time / 3600000) % 24);
    String millisecondsStr = (milliseconds < 10 ? "00" : (milliseconds < 100 ? "0" : "")) + milliseconds;
    String secondsStr = (seconds < 10 ? "0" : "") + seconds;
    String minutesStr = (minutes < 10 ? "0" : "") + minutes;
    String hoursStr = (hours < 10 ? "0" : "") + hours;
    return new String(hoursStr + ":" + minutesStr + ":" + secondsStr + "." + millisecondsStr);
    }

  • Question concerning SimpleDateFormat returning week information

    Hello,
    I am just trying to get returned a date value with the format 'ww/yyyy' and experience problems in getting the correct value around the turn of the year.
    Example:
    java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("w/yyyy");
    df.getCalendar().setFirstDayOfWeek(java.util.Calendar.MONDAY);
    df.getCalendar().setMinimalDaysInFirstWeek(4);
    System.out.println(df.format(new java.sql.Date(103,11,31))); //Dez, 31, 2003As output I get "01/2003" which is not correct - I expected "01/2004" instead.
    How do I get the correct output?
    Do I have miscoded there something or is this a bug?
    BTW: when trying the same with Jan, 1, 2004 I get the correct output.
    Thank you for any answers
    Ralf

    From the API documentation for java.util.Calendar:
    "The first week of a month or year is defined as the earliest seven day period beginning on getFirstDayOfWeek() and containing at least getMinimalDaysInFirstWeek() days of that month or year."
    So, since December 31 2003 was on a Wednesday and you've defined your weeks to start on Monday, there were 3 days of 2003 and 4 days of 2004 in the week containing that date. And since your "minimal days in first week" is defined to be 4, this week is the first week of 2004. In other words, its week number is 1.
    So that's why you see week number 1. (A week has only one week number.)
    And since December 31 2003 was in 2003, you see 2003 for the year.
    If you experiment a bit more with GregorianCalendar and callcal.get(Calendar.WEEK_OF_YEAR)for various dates, you should see what is going on.
    If you want the "correct" output (in other words the output you want to see, whatever it is) then you can subclass GregorianCalendar and override its get method.

  • SimpleDateFormat: when day of month becomes day of week

    I have a weird situation where the SimpleDateFormat class seems to interpret the "dd" mark as day of week instead of day of month when I use a certain pattern. The following code demonstrates the problem:
    public class ByteTest {
        public static final String PATTERN = "mm HH dd MM F";
        // public static final String PATTERN = "dd MM yyyy";
        public static void main(String [] args) throws Exception {
            String str = "11 11 08 11 1";
            // String str = "24 11 2004";
            System.out.println(strToDate(str, PATTERN));
        public static Date strToDate(String date, String pattern) throws ParseException {
            SimpleDateFormat formatter = new SimpleDateFormat(pattern);
            formatter.setLenient(false);
            return formatter.parse(date);
    }The result (at least for me) is:
    Exception in thread "main" java.text.ParseException: Unparseable date: "11 11 08 11 1"
    at java.text.DateFormat.parse(DateFormat.java:335)
    at ByteTest.strToDate(ByteTest.java:20)
    at ByteTest.main(ByteTest.java:14)
    When I change "dd" from 08 to 07, I get this:
    Sat Nov 07 11:11:00 EET 1970
    ...and finally, when I change the pattern (done here by uncommenting the commented lines and commenting the ones above them), I get:
    Wed Nov 24 00:00:00 EET 2004
    So, as you can see, for some reason "dd" is interpreted as day of week number in the weirder pattern (which unfortunately we have to use in a pattern matching thing we are using). Any ideas?
    When I comment the line with setLenient(false), it also works fine, but unfortunately we need to use that flag because otherwise users could input weird values for the various fields.
    I tried adding Locale.UK to the parsing method, but that made no difference so clearly my locale (+02:00 GMT) is not at fault.
    I also considered if the day might be out of range since using this pattern we get year 1970, but clocks start counting from 1.1.1970 right? So that doesn't seem a likely cause either. :-/
    The markers for day of week in SimpleDateFormat are E and F; so I guess the question is, when does d become E or F...

    I'm not sure I quite understand what the problem is... the reason why you can't parse that date is that it's invalid, Sunday November 8 on 1970 goes to the second week of the month, so day-of-week-in-month is 2, not 1.. so the string you should pass is "11 11 08 11 2"

  • Integer- double and a question about time

    Hello!
    I have two questions
    1) I have two integers int1 and int2 I want to to int1/int2---> get a number of type 00.0 (double) is there a simple way to achieve this?
    2) I want to get time (just time) of the format 23:01 is there a simple way to achieve this
    Thanks in advance

    1) Yes:
    double frac = (double)int1 / (double)int2;2) Yes: SimpleDateFormat
    Andre

  • Date Question

    I need to run a query to get certain information from my Oracle table that's over 9 months old. My query doesn't seem to be working properly. Below is my query:
    ---Getting today's date----
    currentDate = new SimpleDateFormat("MM/dd/yyyy").format(new java.util.Date());
    -----query to check for drawings that are over 9 months old-------
    queryRptchoice = "SELECT Drawing.dwgID, Personnel.prsnlID, Drawing.PMDwgNum, Drawing.dwgSize,";
    queryRptchoice += " Drawing.Title, Personnel.fname, Personnel.lname, Checked_Out.modNum,";
    queryRptchoice += " Checked_Out.chkoutDate, Checked_Out.Project, Checked_Out.AEFirm, Checked_Out.AEName";
    queryRptchoice += " FROM AJM.Drawing, AJM.Personnel, AJM.Checked_Out WHERE Drawing.dwgID = Checked_Out.dwgID";
    queryRptchoice += " AND Checked_Out.prsnlID = Personnel.prsnlID AND Drawing.isCheckedOut = 'yes'";
    queryRptchoice += " AND Checked_Out.isCheckedOut = 'yes'";
    queryRptchoice += " AND chkoutDate <= TO_DATE('" + currentDate + "', 'MM/DD/YYYY')";
    queryRptchoice += " AND chkoutDate < ADD_MONTHS(TO_DATE('" + currentDate + "', 'MM/DD/YYYY'), -9)";
    Any help would be greatly appreciated.

    This is a common question. Go into the JDBC forum and put the words date and oracle in the search forum box. Press search. You have a few options. You can format the date differently or use a preparedstatement.

  • SimpleDateFormat.toLocalizedPattern()

    Howdy Folks?
    I'm using the following: -
    SimpleDateFormat sdf1 = new SimpleDateFormat();
    System.out.println( sdf1.toLocalizedPattern() );
    SimpleDateFormat s1 = new SimpleDateFormat( sdf1.toLocalizedPattern(), Locale.getDefault() );The print out gives me this: - dd/MM/yy HH:mm.
    I can work with this no problem.
    I can also work with MM/dd/yy HH:mm no problem if that is the way it returns the String.
    My question is this: -
    Will it always be one of those TWO patterns?
    Can it be any other pattern?
    What OS settings would result in a different pattern (apart from the obvious time zone one which determines month first or day first)?
    My tests are ok for these but I'm very worried that on some systems it may return a different pattern which will cause me a ParseException later in my program.
    Note: - This code will only be used on MS Windows.
    Hoping you can help.
    Thanks so much
    J

    Good advice with the getAvailableLocals actually. However there are still too many unknowns and potential 'red-herrings' with my technique in general..
    I've gotten over the problem at the source, i.e. ensuring that the date I need to process is always the same format. Bit easier that way I think, given that I did have the luxury of doing this.
    Thanks for the Help DrClap.

  • JFileChooser and date format questions

    I have a JFileChooser that currently works - I set the default directory and allow the user to select a file or enter a file name.
    I have been asked to modify this to prepopulate the file name field on the JFileChooser.
    How do I do that? It is not obvious which method to call to set the filename field.
    Also, the file name needs to be a timestamp "*yyyyMMddHHmmss*.dat"
    I tried creating the timestamp part with the following code, but it does not format as expected.
            String s = "";
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddddHHmmss");
            try
                java.util.Date now = new java.util.Date();
                java.util.Date dat = dateFormat.parse( now.toString() );
                s = dat.toString();
            }What is wrong with this?
    Thanks.

    I don't do Swing and this is also not the subforum for Swing questions. It has its own subforum.

  • SimpleDateFormat

    I have a quick question about SimpleDateFormat. Here's a bit of code:
    Calendar cal = Calendar.getInstance();
    java.util.Date date = cal.getTime();
    String myDate = DateFormat.getDateInstance().format(date);
    SimpleDateFormat goformat = new SimpleDateFormat("MMM d, yyyy");
    // I am catching this Exception, but left it off here
    java.util.Date Date1 = goformat.parse(myDate);
    System.out.println(myDate);
    System.out.println(Date1);This is the output I am getting:
    Jun 21, 2005 // I have the date on my computer in this format
    Tue Jun 21 00:00:00 CDT 2005
    Why isn't Date1 the same? Should I change myDate into numbers, i.e. 6/21/2005, and then parse it?
    Thanks

    They are the same. You specified a certain formatting for the String in your SimpleDateFormat initializer. Then, you printed that exact formatting. Date.toString() has its own formatting. You can verify this by trying:
    static final public void main(final String[] args) {
            try {
                 Date date = new Date();
                 Calendar calendar = Calendar.getInstance();
                 calendar.setTime(date);
                 SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd kk:mm:ss zzz yyyy");
                 System.out.println(formatter.format(date));
                 System.out.println(date.toString());
             catch (Throwable e) {     
                 e.printStackTrace();
        }- Saish

  • SimpleDateFormat rolling 1 hour too early for Fall 2003?

    Hey all...
    My question deals with the SimpleDateFormat object, more specifically given a time in NY ( that rolls from EST to EDT and back to EST in the fall)
    Currently the following code (borrowed from a previous post) works perfectly for the Spring transition from EST to EDT, i.e. GMT-5 to GMT-4 on April 6. But it seems to roll back to GMT-5 at 1AM for October 26, as opposed to 2AM as I would expect. Does anyone know why this happens?
    any help would be appreciated.
    thanks.
    import java.util.SimpleTimeZone;
    import java.text.SimpleDateFormat;
    import java.text.DateFormat;
    import java.text.ParseException;
    import java.util.Date;
    import java.util.TimeZone;
    import java.io.*;
    public class GMTTimeUtil {
         public static final SimpleDateFormat sdf =
         new SimpleDateFormat( "yyyyMMddHHmm" );
         static BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) );
         public static final SimpleDateFormat formatter =
         new SimpleDateFormat( "yyyyMMddHHmm" );
         static {
              sdf.setTimeZone( TimeZone.getTimeZone( "GMT+00:00" ) );
         public static void main( String[] args ) {
              Date param = null;
              System.out.println( "Enter a time: (yyyyMMddHHmm )" );
              try {
              param = formatter.parse( in.readLine() );
              System.out.println( "The time in Greenwich based on input is: " + getGMTTime( param ) );
              } catch( Exception e) {
         public static String getGMTTime( Date param ) {
              System.out.println( "The time passed into this function is:" + param );     
              return sdf.format( param );

    This may be of interest.
    import java.util.*;
    import java.text.*;
    public final class EST_EDT{
    public static void main(String[] args) throws java.lang.Exception{
      java.text.SimpleDateFormat form = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm z");
      TimeZone zone = TimeZone.getTimeZone("America/New_York");//behavior is different when SimpleTimeZone zone = new SimpleTimeZone(offset,ID);
      System.out.println(zone.getID());
      GregorianCalendar cal = (GregorianCalendar)Calendar.getInstance(zone);
      cal.setTimeZone(zone);
      form.setCalendar(cal);
      long t0 = 1067144400000L;
      System.out.println(t0);
    for(int j=0;j<12;j++){
          cal.setTimeInMillis(t0+j*10*60*1000L);// increment of 10 minutes
          System.out.println(form.format(cal.getTime()));
    }

  • SimpleDateFormat 'S'

    My question regards using SimpleDateFormat to parse a Date object from a millisecond representation.
    The issue at hand is that I have a module that parses objects out of an XML representation where one of the tag attributes is a timestamp. The parser module can be configured such that the format of this timestamp is specified. No problem so far - however it is possible that one of the sources of the xml text gives the timestamp attribute in millisecond format: i.e. 93748404743.
    In SimpleDateFormat the 'S' symbol is for milliseconds, but not for the 'long' millisecond representation - rather for the milliseconds within the current second. That is, the range of acceptable values for the S portion of a formatted date is 0-999.
    Does anyone know of a way to have SimpleDateFormat to pickup this 'long' formatted date string?
    dlgrasse

    the previous two posts seem to point at doing a extra 'if' check. something like:
    Date timestamp = null;
    try
      long timestampLong = Long.parseLong (tstampStr);
      timestamp = new Date (timestampLong); // don't fuss if this is deprecated please :}
    catch (NumberFormatException nfe)
      timestamp = MY_SIMPLE_DATE_FORMAT.parse (timestampStr);
    }hmmm...if i don't get any better response i'll consider this route. however, from a programming point of view i hesitate because this uses 'exception handling as logic control'...something i personaly disdain and accept as bad practice.
    dlgrasse

  • How To Declare SimpleDateFormat!

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    public class Grid extends JFrame /*implements ActionListener*/
    private JPanel date_panel,year_panel, month_panel,day_panel;
    private String time=new String("");
    private Date date=new Date();
    Hey !
    i am getting an error massege"cannot resolve the symbol'simpleDateFormat' ".
    i think i have to declare it first ,i tried but could not come up with a solution.
    please somebody help me!thanks
    public Grid() {
    time=time + new Date().toString();
    /*//time=java.text.SimpleDateFormat ;
              // Format the current time.
              SimpleDateFormat formatter
              = new SimpleDateFormat ("MM/dd/yy");
         //     Date time = new Date();
         //     String dateString = formatter.format(time);*/
         SimpleDateFormat formatter = new SimpleDateFormat("E, MMMM d, yyyy") ;
         time = formatter.format(date) ;
              date_panel.add(new JLabel(time)) ;
              year_panel=new JPanel();
              month_panel=new JPanel();
              day_panel=new JPanel();
              date_panel.setLayout(new FlowLayout());
              date_panel.add(new JLabel(time));
              Container contentPane = getContentPane();
              contentPane.setLayout(new GridLayout(1,4));
    contentPane.add(date_panel);
    public static void main(String args[]) {
              Grid gw = new Grid();
         gw.setTitle("Date Slider");
              gw.setSize(400,200);
              gw.setVisible(true);
    }

    you have to add
    import java.text.SimpleDateFormat;
    to your code, for javac to find the definition of java.text.SimpleDateFormat.
    If you have any further questions don't hesitate to ask.

  • Return java SimpleDateFormat type instead of the default xs:dateTime format

    It is possible to return a date timestamp in the java SimpleDateFormat instead of xs:dateTime in a data service?
    If so, how would I go about doing this? Thanks.

    I don't understand the question. xs:dateTime is an xquery type and SimpleDateFormat is a java class. You don't have both in Xquery and you don't have both in java, so when you say 'return' I don't know what you mean. Do you mean as the return type (or part of the return type) of an xquery function? The answer is 'no' - you can only return xquery types. If your client needs it, you could pass it around as an xs:string in xquery, and your client could convert it from a string to a SimpleDateFormat.

Maybe you are looking for