I have a String variable as a date type.for example:
String myDate= "20130403";
and I want to separate it to 3 different date formats like this:
String myDay = "03";
String myMonth= "04";
String myYear= "2013";
how is the fastest way to separate my String?
thanks
String yourDateString = "20130403";
SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");
Date currentDate = sd.parse(yourDateString);
Calendar cal = Calendar.getInstance();
cal.setTime(currentDate);
String year = String.valueOf(cal.get(Calendar.YEAR)) + "";
// As Gyro said month start at 0 to 11.
String month = String.valueOf(cal.get(Calendar.MONTH)+1) + "";
String day = String.valueOf(cal.get(Calendar.DAY_OF_MONTH)) + "";
If this is a fixed format simply use substring.
String myDate= "20130403";
String myYear = myDate.substring(0,4);
String myMonth= myDate.substring(4,6);
String myDay= myDate.substring(6,8);
System.out.println(myDay);
System.out.println(myMonth);
System.out.println(myYear);
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