• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 210
  • Last Modified:

simple date question

String mySDate = "Sa, 09.10.2004";

How can i convert this as

Date myDDate = new Date("09.10.2004");
             
0
sangeetha
Asked:
sangeetha
  • 9
  • 7
  • 5
  • +1
1 Solution
 
expertmbCommented:
use DateFormat
0
 
cjjcliffordCommented:
import java.text.SimpleDateFormat;

...

SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy" );
Date myDDate = format.parse( mySDate );
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
sangeethaAuthor Commented:
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
 
cjjcliffordCommented:
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
 
expertmbCommented:
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
 
expertmbCommented:
only Date() is kept other constructors are deprecated.
0
 
cjjcliffordCommented:
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
 
sangeethaAuthor Commented:
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
 
expertmbCommented:
                 String mySDate = "SA,09.10.2004";

                  mySDate = mySDate.substring(3,mySDate.length());
0
 
expertmbCommented:
>>new SimpleDateFormat("EE, dd.MM.yyyy" ).format( mySDate )
cjjclifford - not worked :(
0
 
cjjcliffordCommented:
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
 
expertmbCommented:
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
 
cjjcliffordCommented:
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
 
zzynxSoftware engineerCommented:
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
 
cjjcliffordCommented:
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
 
zzynxSoftware engineerCommented:
>> 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
 
cjjcliffordCommented:
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
 
cjjcliffordCommented:
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
 
zzynxSoftware engineerCommented:
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
 
zzynxSoftware engineerCommented:
This way even the (exact number of) spaces are considered
0
 
cjjcliffordCommented:
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
 
zzynxSoftware engineerCommented:
Thanks for accepting
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 9
  • 7
  • 5
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now