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?
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?
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);
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
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);
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);