Solved

simple date question

Posted on 2004-10-06
23
199 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 9
  • 7
  • 5
  • +1
23 Comments
 
LVL 6

Expert Comment

by:expertmb
ID: 12236519
use DateFormat
0
 
LVL 11

Expert Comment

by:cjjclifford
ID: 12236528
import java.text.SimpleDateFormat;

...

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

Expert Comment

by:expertmb
ID: 12236551
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!

 
LVL 2

Author Comment

by:sangeetha
ID: 12236561
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
ID: 12236639
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
ID: 12236647
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
ID: 12236655
only Date() is kept other constructors are deprecated.
0
 
LVL 11

Expert Comment

by:cjjclifford
ID: 12236704
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
ID: 12236712
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
ID: 12236753
                 String mySDate = "SA,09.10.2004";

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

Expert Comment

by:expertmb
ID: 12236783
>>new SimpleDateFormat("EE, dd.MM.yyyy" ).format( mySDate )
cjjclifford - not worked :(
0
 
LVL 11

Expert Comment

by:cjjclifford
ID: 12237009
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
ID: 12237143
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
ID: 12237193
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
ID: 12242868
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
ID: 12246025
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
ID: 12246108
>> 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
ID: 12246251
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
ID: 12246277
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
ID: 12246415
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
ID: 12246418
This way even the (exact number of) spaces are considered
0
 
LVL 11

Expert Comment

by:cjjclifford
ID: 12246468
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
ID: 12295208
Thanks for accepting
0

Featured Post

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

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

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
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 tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

630 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