How to extract Day, Month and Year values from a string [like 18/08/2012]. I tried using SimpleDateFormat, but it returns a Date object and I observed that all the Get methods are deprecated. Is there any better way to do this?
Thanks
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
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With