Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

separating a string in to 3 different string variables in java

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

like image 303
A R Avatar asked May 31 '26 04:05

A R


2 Answers

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)) + "";
like image 68
Rollyng Avatar answered Jun 01 '26 19:06

Rollyng


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);
like image 39
Kevin Bowersox Avatar answered Jun 01 '26 20:06

Kevin Bowersox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!