Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Month String to Integer in Java

Given a month string such as:

    "Feb" or     "February" 

Is there any core Java or third party library functionality that would allow you to convert this string to the corresponding month number in a locale agnostic way?

like image 928
Dylan Cali Avatar asked Feb 15 '10 21:02

Dylan Cali


People also ask

How to convert month to int java?

setTime(date); int month = cal. get(Calendar. MONTH); System.

How to convert month in words to number in java?

// displaying month number Format f = new SimpleDateFormat("M"); String strMonth = f. format(new Date()); System. out. println("Month Number = "+strMonth);

How do I convert a date to an integer in java?

Or, if you really want to convert the 'date' into integer type 06/03/2017 to 06032017 .. you can do something like this. SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy"); System. out. println(Integer.

How do you convert months to months and years in java?

Extract the number of years and of months. int years = period. getYears(); int months = period. getMonths();


Video Answer


1 Answers

You could parse the month using SimpleDateFormat:

    Date date = new SimpleDateFormat("MMM", Locale.ENGLISH).parse("Feb");     Calendar cal = Calendar.getInstance();     cal.setTime(date);     int month = cal.get(Calendar.MONTH);     System.out.println(month == Calendar.FEBRUARY); 

Be careful comparing int month to an int (it does not equal 2!). Safest is to compare them using Calendar's static fields (like Calendar.FEBRUARY).

like image 137
Bart Kiers Avatar answered Sep 19 '22 18:09

Bart Kiers