2

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
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
Nabin Khatiwada
  • 478
  • 5
  • 15
  • Instead, You can have Java way to do this. this link may help you. http://stackoverflow.com/questions/6510724/how-to-convert-java-string-to-date-object – nanithehaddock Jun 14 '16 at 05:42

5 Answers5

5

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();
}
Divyesh Boda
  • 258
  • 2
  • 12
1

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);
}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
1

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();
        }
prashant0205
  • 269
  • 1
  • 3
  • 17
0

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();
        }
Sachin
  • 1,307
  • 13
  • 23
0

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();
        }
Pramod Waghmare
  • 1,273
  • 13
  • 21