-1

I have these strings

String day1 = "June 3, 2015";

and

String day2 = "June 25, 2015";

I want create a method to parse out the month, day and year. Currently I am using substring() but think there may be a better solution?

user1607549
  • 1,499
  • 3
  • 13
  • 17

4 Answers4

1

Use SimpleDateFormat and parse the date from there.

SimpleDateFormat format = new SimpleDateFormat("MMMM d, yyyy");
Date date1 = format.parse(day1);
Date date2 = format.parse(day2);
cbender
  • 2,231
  • 1
  • 14
  • 18
0

Note this is equivalent to MMMM dd, yyyy

Try this.

SimpleDateFormat sdf = SimpleDateFormat("MMMM dd, yyyy");
Date parsed = sdf.parse(day1, new ParsePosition(0));
...

Ps: I am not tried this code, please, feel free to comment anything.

Reference SimpleDateFormat

Roberto Tellez Ibarra
  • 2,146
  • 3
  • 18
  • 34
-1

Solution 1 :

Use StringTokenizer to tokenize the string For example :

String str = "June 3, 2015";
StringTokenizer defaultTokenizer = new StringTokenizer(str);
while (defaultTokenizer.hasMoreTokens())
{
    System.out.println(defaultTokenizer.nextToken());
}

Remove ',' from date i.e 2nd token using deletecharAt(int index);

Hope that works for you

Solution 2 : Using split() method

for (String retval: Str.split(" ", 3)){
         System.out.println(retval);
}

split() takes two argument first it will take the token , and the limit is how many strings. still you have to remove ',' .

There is another easiest solution : Solution 3 :

SimpleDateFormat format = new SimpleDateFormat("MMMM d, yyyy");
Date date1 = format.parse(day1);
Date date2 = format.parse(day2);
Sohil Omer
  • 1,171
  • 7
  • 14
  • The [JavaDoc](http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html) says: *`StringTokenizer` is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the `split` method of `String` or the `java.util.regex` package instead.* – RealSkeptic Jul 20 '15 at 18:42
-1

you can try something like

private static final String DAY = "dd";
private static final String MONTH = "MM";
private static final String YEAR = "yyyy";//use the format you want this just an example
Format month = new SimpleDateFormat(MONTH);
Format day = new SimpleDateFormat(DAY);
Format year = new SimpleDateFormat(YEAR);
month.format(your date); 
day.format(your date); 
year.format(your date);
sunny
  • 303
  • 2
  • 7