Solved

Java Date  How to convert String to DATE

Posted on 2004-04-07
17
339,099 Views
Last Modified: 2012-05-04
Hi

Iam trying to Conver a String(mm/dd/yyyy) to Date
Here is code
DateFormat myDateFormat = new SimpleDateFormat(strFormat);
Date myDate = null;
try {
     myDate = myDateFormat.parse(strDate);
} catch (ParseException e) {
     System.out.println("Invalid Date Parser Exception ");
     e.printStackTrace();
}
System.out.println("Finished Date Function " + myDate.getDay());

My Problem is iam passing 4/6/2004

but return value month is coming as 2 how to get Day of the Month

0
Comment
Question by:LakshmanaRavula
17 Comments
 

Author Comment

by:LakshmanaRavula
ID: 10776992

Here is the values
 format = "MM/dd/yyyy"
 date    = 4/6/2004
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10776999
>>My Problem is iam passing 4/6/2004

Well the format String should then be

strFormat = "m/d/yyyy";

or

strFormat = "d/m/yyyy";


0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10777011
Sorry, in that case

strFormat = "M/d/yyyy";
0
Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

 

Author Comment

by:LakshmanaRavula
ID: 10777035
I tried this option but still returning 2 as value when i send date as

Here is Debug Staments
inside Date Function : 4/6/2004--m/d/yyyy
Date is  : Tue Jan 06 00:04:00 EST 2004
Finished Date Function  val is = 2
Day Num Returned is : 2
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10777054
Sunday = 0
mondY = 1

ETC.
0
 

Author Comment

by:LakshmanaRavula
ID: 10777056
Still same problem

inside Date Function : 4/26/2004--M/d/yyyy
Date is  : Mon Apr 26 00:00:00 EDT 2004
Finished Date Function  val  is = 1
Day Num Returned is : 1
0
 

Author Comment

by:LakshmanaRavula
ID: 10777065
Ok in that case how can get Day of the Month
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 200 total points
ID: 10777074
If that's what you want, this is the way to do it

Calendar cal = Calendar.getInstance();
int dayNumber = cal.get(Calendar.DAY_OF_WEEK);
int date = cal.get(Calendar.DATE);
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10777087
(after setting the cal with your date)

cal.setTime(yourDate);
0
 

Author Comment

by:LakshmanaRavula
ID: 10777094
Thats cool  Can you please tell me how can pass String date to Calendar
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10777113
You can't. Use the formatting technique and parse as you're already doing
0
 

Author Comment

by:LakshmanaRavula
ID: 10777165
got it Thank you
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10777272
8-)
0
 

Expert Comment

by:go2tapan
ID: 10974884
System.out.println("Finished Date Function " + myDate.getDate());

answer to your problem
0
 
LVL 1

Expert Comment

by:mlpk_tyr
ID: 11741819
actually the getDay() method will return the order of the day in the week so it returns 2 which is Tuesday . since u have given April 6th which is actually Tuesday. so try

myDate.getDate();

Also when you are parsing the string for  Date using SimpleDateFormat make sure u add this line too,

myDateFormat.setLenient(false); like below


try {
     myDateFormat.setLenient(false);
     myDate = myDateFormat.parse(strDate);
} catch (ParseException e) {
     System.out.println("Invalid Date Parser Exception ");
     e.printStackTrace();
}


as it would prevent the automatic conversion of the java to add one to the mext date is u have exceeded the Date for the given month.

ie.. if u give 31 and month as 4(April) which really has 30 days only then ur date will be shown as 1 may.

hope this will work.
0
 

Expert Comment

by:RdeLange
ID: 14421172
The comple story from date to string and back is:

            prt("Date is 25 may 2007");
            prt("25/05/05");
            SimpleDateFormat sim = new SimpleDateFormat("dd/MM/yy");
            java.util.Date datum = new java.util.Date();
            try{
                  datum = sim.parse("25/05/05");
            }catch(ParseException e){}      
            prt("Java data object is"+datum);
            prt("");
            prt("datum formatted is then ...");
            
            
            SimpleDateFormat dmj= new SimpleDateFormat("dd/MMM/yyyy");
                   
        String thisDate = dmj.format(datum);
        prt("And after all it's this string:"+thisDate);
            
      }
      public void prt(String s){System.out.println(s);      }
0
 

Expert Comment

by:DSEyers
ID: 20207628
One caveaty of the above posts to be aware of is if the first part of the string mattches the pattern a valid date will be returned.  Below is a DateTimeUtil method I created to specify whether the whole string should be matched or not.  So I can choose if date format pattern "dd/mm/yyyy" should throw an exception when the value "10/10/2007HelloWorld" is passed.  You can not rely on text.length() as a format pattern may have things like mmm which may evaluate to September etc.

      /**
       * Get Date from Text using the date format specified
       * @param dateAsText Text date portion
       * @param dateFormat Format the date in text is stored as
       * @param matchWholeString If you want an error to be thrown when a match is found and text exists after the pattern has been matched on the date as text value passed</b>
       * <p>
       * e.g.<br/>
       *       Pattern: dd/mm/yyyy<br/>
       *       Value:   10/10/1977HelloWorld
       * </p>
       * @return Date representation of the text date passed
       * @throws ParseException if text date can not be converted to a date using the format passed
       */
      public static Date getDateFromString(final String dateAsText, final String dateFormat, final boolean matchWholeString) throws ParseException {
        final DateFormat df = new SimpleDateFormat(dateFormat);
            df.setLenient(false);
            final ParsePosition parsePosition = new ParsePosition(0);
            final Date date = df.parse(dateAsText, parsePosition);
            
            // Check ParsePosition is to end of string, otherwise throw ParseException error
            if (matchWholeString && parsePosition.getIndex() < dateAsText.length()) {
                  throw new ParseException("Date pattern '" + dateFormat + "' when resolved and applied to date text '"
                              + dateAsText + "' does not match whole of text string passed, only to position " + parsePosition.getIndex(), parsePosition.getIndex());
            }
        return date;
    }
0

Featured Post

ScreenConnect 6.0 Free Trial

Discover new time-saving features in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI, app configurations and chat acknowledgement to improve customer engagement!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
micro services spring boot application error 3 199
java stored proc example 9 32
Desingning Refactoring existing code 2 24
Which non-HTML GUI front end to use with Java? 3 22
For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

832 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question