nicky_1525
nicky_1525

Reputation: 959

How to get month number from month string in Java?

I've got this string

23/Gennaio/2014

and I need this other string

23/01/2014

I tried using joda.time:

DateTimeFormatter format =  DateTimeFormat.forPattern("dd/MMM/yyyy").withLocale(Locale.ITALY);
DateTime instance = format.parseDateTime("23/Gennaio/2014");  
String month_number = String.valueOf(instance.getMonthOfYear());

But I get this exception:

01-06 13:31:55.341: E/AndroidRuntime(1116): java.lang.IllegalArgumentException: Invalid format: "23/Gennaio/2014"

What am I missing?

Upvotes: 2

Views: 5816

Answers (5)

Basil Bourque
Basil Bourque

Reputation: 339332

Lowercase g

The G in “Gennaio” should be lowercase g: gennaio is the month name in Italian.

java.time

In modern Java, use the java.time classes for your date-time handling.

The Joda-Time project is now in maintenance-mode. The project recommends migrating to its official successor, the java.time classes defined in JSR 310, built into Java 8+.

Android API level 26+ comes with an implementation of java.time. For earlier Android, the latest tooling provides most of the functionality via “API desugaring”.

Parsing

Represent a date-only value with java.time.LocalDate.

We use Locale to specify the human language and cultural norms needed for localized values such as the name of the month.

Here is code for correct input.

String input = "23/gennaio/2014" ;
Locale locale = Local.of ( "it" , "IT" ) ;
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "dd/MMMM/uuuu" ).withLocale ( locale ) ;
LocalDate ld = LocalDate.parse( input , f ) ;

From that LocalDate object, you can access the month number, 1-12 for January-December. Or access the Month enum object.

int monthNumber = ld.getMonthValue() ;
Month month = ld.getMonth() ;

Case-insensitive

Here is code for your incorrect input. We must make the formatter case-insensitive. For that we use DateTimeFormatterBuilder to build a DateTimeFormatter object.

String input = "23/Gennaio/2014";
Locale locale = Locale.of ( "it" , "IT" );
DateTimeFormatter f =
        new DateTimeFormatterBuilder ( )
                .parseCaseInsensitive ( )
                .appendPattern ( "dd/MMMM/uuuu" )
                .toFormatter ( locale );
LocalDate ld = LocalDate.parse ( input , f );

int monthNumber = ld.getMonthValue ();
Month month = ld.getMonth();

When run:

2014-01-23
monthNumber = 1
month = JANUARY

ISO 8601

Educate the publisher of your data about using standard ISO 8601 standard formats when communicating date-time values textually. No need to invent your own formats. And never use localized formats for data-exchange.

LocalDate ld = LocalDate.parse ( "2014-01-23" ) ;  // Standard format.
String output = ld.toString() ;  // Standard format.

Upvotes: 1

Meenal
Meenal

Reputation: 2877

Use this code

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    String dateString = "23/Gennaio/2014";


     Log.i("meenal","Date 2:"+localizeDate(dateString, Locale.ITALY));


}

private String localizeDate(String inputdate, Locale locale) { 

    Date date = new Date();
    SimpleDateFormat dateFormatCN = new SimpleDateFormat("dd/MMM/yyyy", locale);       
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");


    try {
        date = dateFormatCN.parse(inputdate);

        Log.i("meenal", "Date:"+date);
    } catch (Exception e) {
        Log.e("meenal", e.getMessage(),e);
        return inputdate;
    }
    return dateFormat.format(date);
}

Upvotes: -1

venergiac
venergiac

Reputation: 7717

why not pure java?

 SimpleDateFormat formatIn = new SimpleDateFormat("dd/MMM/yyyy", Locale.ITALY);
 Date instance = formatIn.parse("23/Gennaio/2014");  
 SimpleDateFormat formatOut = new SimpleDateFormat("dd/MM/yyyy", Locale.ITALY);

 System.out.println(formatOut.format(instance));

 String month_number = String.valueOf(instance.getMonth()); //DEPRECETDE USE CALENDAR

result is "23/01/2014"

Upvotes: 0

Phantômaxx
Phantômaxx

Reputation: 38098

23/Gennaio/2014 is not a valid date string to be parsed.
Try 23/gennaio/2014 and try to parse it with "dd/MMMM/yyyy" format (add an M)

Upvotes: 2

assylias
assylias

Reputation: 328737

It seems to expect the month name in lower case (not sure why):

DateTime instance = format.parseDateTime("23/Gennaio/2014".toLowerCase(Locale.ITALIAN));

should work better.

Upvotes: 5

Related Questions