Solved

simple date question

Posted on 2004-10-06
23
185 Views
Last Modified: 2010-03-31
String mySDate = "Sa, 09.10.2004";

How can i convert this as

Date myDDate = new Date("09.10.2004");
             
0
Comment
Question by:sangeetha
  • 9
  • 7
  • 5
  • +1
23 Comments
 
LVL 6

Expert Comment

by:expertmb
Comment Utility
use DateFormat
0
 
LVL 11

Expert Comment

by:cjjclifford
Comment Utility
import java.text.SimpleDateFormat;

...

SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy" );
Date myDDate = format.parse( mySDate );
0
 
LVL 6

Expert Comment

by:expertmb
Comment Utility
0
 
LVL 2

Author Comment

by:sangeetha
Comment Utility
try {
            SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
            Date myDDate = sdf.parse("Sa, 09.10.2004");
            System.out.println(myDDate);
        } catch (ParseException e1) {
            e1.printStackTrace();
        }
            
        why this gives me parse exception:
                INFO  [STDOUT] java.text.ParseException: Unparseable date: "Sa, 09.10.2004"
            
0
 
LVL 11

Expert Comment

by:cjjclifford
Comment Utility
The "Sa, " part...

the code snippet I provided was to parse the date for the line you provided:

Date myDDate = new Date("09.10.2004");

Read the JavaDoc pages for java.text.SimpleDateFormat - it gives the full formatter specification (simple to read too!)
0
 
LVL 6

Expert Comment

by:expertmb
Comment Utility
Date (String s) is deprecated

import java.text.*;
import java.util.*;

public class dateFormat{

      public static void main(String [] s){
            try{
                  String mySDate = "09.10.2004";
                  SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy" );
                  Date myDate = format.parse(mySDate );
                  System.out.println(myDate);
            }catch(Exception ex){
                  ex.printStackTrace();
            }
      }
}
0
 
LVL 6

Expert Comment

by:expertmb
Comment Utility
only Date() is kept other constructors are deprecated.
0
 
LVL 11

Expert Comment

by:cjjclifford
Comment Utility
expertmb, that's more or less what I suggested above, and indeed, more or less what the author tried - The parse exception was generated by the String being "Sa, 09.10.2004" not "09.10.2004", so the format rule for the SimpleDateFormat should be changed to include the day

probably new SimpleDateFormat("EE, dd.MM.yyyy" ).format( mySDate ) will do the trick, but untested...
0
 
LVL 2

Author Comment

by:sangeetha
Comment Utility
I have:

mySDate = "Sa, 09.10.2004"; (I should not chnage it for any reason.)

Now i want to extract just the Date part("09.10.2004") of that string. Is it possible?
0
 
LVL 6

Expert Comment

by:expertmb
Comment Utility
                 String mySDate = "SA,09.10.2004";

                  mySDate = mySDate.substring(3,mySDate.length());
0
 
LVL 6

Expert Comment

by:expertmb
Comment Utility
>>new SimpleDateFormat("EE, dd.MM.yyyy" ).format( mySDate )
cjjclifford - not worked :(
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 11

Expert Comment

by:cjjclifford
Comment Utility
oops... should have been ".parse()"...

but actually, the "EE" part doesn't work, has to be specified as "EEE", and the date then has to be "Sat, 09.10.2004":

System.out.println( new SimpleDateFormat("EEE, dd.MM.yyyy" ).parse( "Sat, 09.10.2004" ) )

if the Day part can't be changed, then the substring suggestion is the approach to take...
0
 
LVL 6

Expert Comment

by:expertmb
Comment Utility
try{
      String mySDate = "SAT,09.10.2004";
      //mySDate = mySDate.substring(3,mySDate.length());
      SimpleDateFormat format = new SimpleDateFormat("EEE,dd.MM.yyyy" );
      Date myDate = format.parse(mySDate );
      System.out.println(myDate);
      System.out.println(format.format(new Date()));
}catch(Exception ex){
      ex.printStackTrace();
}
0
 
LVL 11

Expert Comment

by:cjjclifford
Comment Utility
yup, like I posted above.

but, as the author said:

I have:

mySDate = "Sa, 09.10.2004"; (I should not chnage it for any reason.)


so, to get the SimpleDateFormat( "EEE, dd.MM.yyyy" ) to work, the "Sa, 09.10.2004" would have to be changed to "Sat, 09.10.2004"

if this is possible, use SimpleDateFormat( "EEE, dd.MM.yyyy" ).parse( mySDate )

otherwise use SimpleDateFormat( "dd.MM.yyyy" ).parse( mySDate.substring( 4, mySDate.length() ) );

(note 4, as there is a space after the comma in the author's date string!)

Cheers,
C.
0
 
LVL 37

Accepted Solution

by:
zzynx earned 20 total points
Comment Utility
Lots of methods can lead to the same result.
This is another one:

        String mySDate = "Sa, 09.10.2004";
        mySDate = mySDate.replaceAll("\\D","");  // remove all non-digit characters

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");
            Date d = sdf.parse( mySDate );
            System.out.println(d);
        } catch (ParseException ex) {
            ex.printStackTrace();
        }
0
 
LVL 11

Expert Comment

by:cjjclifford
Comment Utility
well... I would try and keep to something that parses the exact format expected (which the substring() sort of does), as otherwise a String that just happens to contain 8 digits randomly distributed through the string would pass the replaceAll() correctly, and then get parsed by the DateFormat correctly...
Probably the best would be to generate a Regular expression to parse the 2 character day name, and the comma, returning the date portion of the string, which would then be passed to the DateFormat - if the day-name part doesn't parse correctly, throw a ParseException...
0
 
LVL 37

Expert Comment

by:zzynx
Comment Utility
>> a String that just happens to contain 8 digits randomly distributed through the string
>> would pass the replaceAll() correctly
Rather weak argument. The basic assumption is of course that the string passed in is correct.
0
 
LVL 11

Expert Comment

by:cjjclifford
Comment Utility
assumptions? are they not the mother of all f*ck ups?

Its always a good idea to program defensively, and testing all preconditions (fixing bugs around incorrect assumptions can be a real pain if they are just assumed), including formats of strings that are going to be parsed (like the example we have - the SimpleDateFormat() will let you know if the date part is incorrectly parsed, so why not just go that little step further and validate the remainder of the string...

The following snippet does that validation, without using a regular expression..

private static Collection VALID_DAYS = Arrays.asList( new String[] { "Mo", "Tu", "We", "Th", "Fr", "Sa", Su" } );
private static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat( "dd.MM.yyyy" );

public Date parseDate( String dateStr ) throws ParseException {
    String[] bits = dateStr.split( "," );
    if( bits.length != 2 || ! VALID_DAYS.contains( bits[0] ) {
        throw new ParseException( "Date format incorrect" );
    }
    else {
        return DATE_FORMAT.parse( bits[1] );
    }
}
0
 
LVL 11

Expert Comment

by:cjjclifford
Comment Utility
note, that code snippet doesn't strip spaces, so the date format here would be, e.g., "Sa,09.10.2004" - use trim() on the split array elements to allow for whitespace, i.e. VALID_DAYS.contains( bits[0].trim() ) and DATE_FORMAT.parse( bits[1].trim() )...
0
 
LVL 37

Expert Comment

by:zzynx
Comment Utility
See your point. Easy done:

        String mySDate = "Sa, 09.10.2004";
        if ( !mySDate.matches("(Mo|Tu|We|Th|Fr|Sa|Su), ((\\d){2}.){2}(\\d){4}") )
            throw new ParseException( "Date format incorrect" );

        mySDate = mySDate.replaceAll("\\D","");  // remove all non-digit characters
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");
            Date d = sdf.parse( mySDate );
            System.out.println(d);
        } catch (ParseException ex) {
            ex.printStackTrace();
        }

This way the String "Fvsfhg09srg1d0dsfg2sdf004qsdv" won't be successfully parsed as 9 oct 2004.
0
 
LVL 37

Expert Comment

by:zzynx
Comment Utility
This way even the (exact number of) spaces are considered
0
 
LVL 11

Expert Comment

by:cjjclifford
Comment Utility
yup, that'd do it (I'm always lazy about regular expressions, expecially when posting - don't like to post then without testing, and at this time in the morning (GMT) I usually make some typoos... :-))
0
 
LVL 37

Expert Comment

by:zzynx
Comment Utility
Thanks for accepting
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This video teaches viewers about errors in exception handling.

771 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now