0

specific date is "2013-11-12".

I want to extract day, month and year from above date. Please let me know how can I extract?

Veer Shrivastav
  • 5,434
  • 11
  • 53
  • 83
PPShein
  • 13,309
  • 42
  • 142
  • 227

6 Answers6

1

You can use split().

Example :

String mydate="2013-11-12"; //year-month-day

String myyear=mydate.split("-")[0];  //0th index = 2013
String mymonth=mydate.split("-")[1]; //1st index = 11
String myday=mydate.split("-")[2];   //2nd index = 12
Hardik Joshi
  • 9,477
  • 12
  • 61
  • 113
1
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

Date testDate = null;

try {
      testDate = sdf.parse("2013-11-12");
}
catch(Exception ex) {
      ex.printStackTrace();
}

int date= testDate.getDate();
int month = testDate.getMonth();
int year = testDate.getYear();
SHASHIDHAR MANCHUKONDA
  • 3,302
  • 2
  • 19
  • 40
1

Create date object from your date string first, like...

String yourDateString = "2013-11-12";
SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd");
Date yourDate = parser.parse(yourDateString);

Now create Calender instance to get further information about date...

Calendar calendar = Calendar.getInstance();
calendar.setTime(yourDate);
int months = calendar.get(Calendar.DAY_OF_MONTH); 
int seconds = calendar.get(Calendar.SECOND); 
// and similarly use calender.getXXX

Hope this helps...

Bhavin Nattar
  • 3,189
  • 2
  • 22
  • 30
umair.ali
  • 2,714
  • 2
  • 20
  • 30
1

you can use substring method to extract the particular characters from the above string like:

String year=date.substring(0,4);   //this will return 2013
String month=date.substring(5,7);  //this will return 11
String day=date.substring(8,10);   //this will return 12
jyomin
  • 1,957
  • 2
  • 11
  • 27
  • your one cannot be correct if "2013-1-1" – PPShein Nov 12 '13 at 06:30
  • it will be set as default 2013-01-01 or if you know the date will be in this order you can change it as String year=date.substring(0,4); //this will return 2013 String month=date.substring(5,6); //this will return 1 String day=date.substring(7,8); //this will return 1 – jyomin Nov 12 '13 at 06:36
1

You can also use Calendar

Calendar calendar = Calendar.getInstance();
calendar.setTime(new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse("2013-11-12"));
int day = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH);
int year = calendar.get(Calendar.YEAR);
the-ginger-geek
  • 7,041
  • 4
  • 27
  • 45
1

You can do it using SimpleDateFormat and Calendar Class.

Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
cal.setTime(sdf.parse("Mon Mar 14 16:02:37 GMT 2011"));// all done

Now you can use this cal Object to do whatever you want. Not just the date, month or year. you cam use it to perform various operations, such as add month, add year etc...

Veer Shrivastav
  • 5,434
  • 11
  • 53
  • 83