I want to convert String Date to integer and get the month from that integer how can I do that??
For Example: I have String Date as:
String date = "15-06-2016";
so how can I get month as:
06 as output in integer
I want to convert String Date to integer and get the month from that integer how can I do that??
For Example: I have String Date as:
String date = "15-06-2016";
so how can I get month as:
06 as output in integer
Using SimpleDateFormate Class you get only month in string than after you convert string to integer
String dateString = "15-06-2016"
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
try {
Date date = sdf.parse(dateString);
String formated = new SimpleDateFormat("MM").format(date);
int month = Integer.parseInt(formated);
} catch (Exception e) {
e.printStackTrace();
}
You don't need to parse that to date to then get the number of the month, that conversion is not necessary (you could but is a waste of memory and computational time).....
use regex, split the string and parsing the 2nd element of the array will get that directly...
public static void main(String[] args) {
String date = "15-06-2016";
String[] calend = date.split("-");
int month = Integer.parseInt(calend[1]);
System.out.println("the month is " + month);
}
You can do it like this:
try
{
String date = "15-06-2016";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date d = sdf.parse(date);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
int month = cal.get(Calendar.MONTH); //YOUR MONTH IN INTEGER
}
catch (ParseException e)
{
e.printStackTrace();
}
You Can try this
it works for me.
String input_date="15-06-2016";
SimpleDateFormat format1=new SimpleDateFormat("dd-MM-yyyy");
Date dt1= null;
try {
dt1 = format1.parse(input_date);
DateFormat format2=new SimpleDateFormat("MM");
String strMonth=format2.format(dt1);
int month=Integer.parseInt(strMonth);
Log.e("date",""+month);
} catch (ParseException e) {
e.printStackTrace();
}
Try this
String startDateString = "15-06-2016";
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
Date startDate;
try {
startDate = df.parse(startDateString);
Toast.makeText(getApplicationContext(),"Month "+(startDate.getMonth() + 1),Toast.LENGTH_LONG).show();
} catch (ParseException e) {
e.printStackTrace();
}