1

I set Japanese date using Locale (e.g. 21 11月 2016) in my android app. But, I want to send that date into "dd-MM-yyyy" (e.g. 21-11-2016) format to my APIs.

When I try to do this I get below exception :

java.lang.IllegalArgumentException: Bad class: class java.lang.String

Below is my code :

public String convertDate(String date) {
    System.out.println("......ORIGINAL DATE....... " + date); // ......ORIGINAL DATE....... 21 11月 2016
    String myFormat = "dd-MM-yyyy"; //In which you need put here
    SimpleDateFormat sdf = new SimpleDateFormat(myFormat, new Locale(getMyLocale())); //Japanese locale is set but tried english too
    System.out.println("......CONVERTED DATE....... " + sdf.format(date)); //should be 21-11-2016 but getting above error
    return sdf.format(new Date(date));
}

Moreover, for US/English Locale it works fine but for Japanese I am getting this error.

VVB
  • 7,363
  • 7
  • 49
  • 83

2 Answers2

4

You need two formatters as below

    String in = "2016年11月 21日";   // really a space here?
    SimpleDateFormat sdf1 = new SimpleDateFormat ("yyyy年MM月 dd日");
    Date d1 = sdf1.parse(in);

    SimpleDateFormat sdf2 = new SimpleDateFormat ("dd-MM-yyyy");

    System.out.println(sdf2.format(d1));
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
1

java.time

You are using the troublesome old legacy date-time classes supplanted by java.time classes.

Define a DateTimeFormatter object to match the pattern of your input strings and specify a Locale for Japan. Parse input string into a LocalDate object. Call LocalDate.parse.

Define a DateTimeFormatter object to match your desired output. Call LocalDate::format to generate a string you desire.

This has been documented many times already in StackOverflow. Please search to find example code and further discussion.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

  • Java SE 8 and SE 9 and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154