Retrieve Month, Day and Year values from a String using Java
Simply go for String.split()
,
String str[] = "18/08/2012".split("/");
int day = Integer.parseInt(str[0]);
int month = Integer.parseInt(str[1]);
..... and so on
Personally I'd use Joda Time, which makes life considerably simpler. In particular, it means you don't need to worry about the time zone of the Calendar
vs the time zone of a SimpleDateFormat
- you can just parse to a LocalDate
, which is what the data really shows you. It also means you don't need to worry about months being 0-based :)
Joda Time makes many date/time operations much more pleasant.
import java.util.*;
import org.joda.time.*;
import org.joda.time.format.*;
public class Test {
public static void main(String[] args) throws Exception {
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy")
.withLocale(Locale.UK);
LocalDate date = formatter.parseLocalDate("18/08/2012");
System.out.println(date.getYear()); // 2012
System.out.println(date.getMonthOfYear()); // 8
System.out.println(date.getDayOfMonth()); // 18
}
}