2016-11-21 327 views
0

我使用语言环境(例如21 11月2016)在我的Android应用程序中设置日期日期。但是,我想将该日期发送到我的API中,以“dd-MM-yyyy”(例如21-11-2016)格式发送。如何将日期日期转换为英文日期格式?

当我尝试这样做,我得到下面的异常:

java.lang.IllegalArgumentException异常:叛逆类:类java.lang.String

下面是我的代码:

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)); 
} 

此外,美国/英国语言环境它工作正常,但对于日语我得到这个错误。

+0

为您解析字符串,那么你应该使用'parse'不'还有format'的'21 11月2016'格式不是'DD-MMM- yyyy' - 尝试使用'dd MM yyyy'格式进行解析,如果那真的是你的字符串 –

+0

请参阅dd-MM-yyyy是我需要它的格式,但是在文本标签上我设置日期如2016年11月21日 – VVB

+0

并且为了解析我得到这个错误java.text.ParseException:Unparseable date:“2016年11月21日”(在偏移量11) – VVB

回答

1

java.time

您正在使用由java.time类代替的麻烦的旧的遗留日期 - 时间类。

定义DateTimeFormatter对象以匹配输入字符串的模式,并为日本指定Locale。将输入字符串解析为LocalDate对象。致电LocalDate.parse

定义一个DateTimeFormatter对象以匹配您所需的输出。请致电LocalDate::format以生成您想要的字符串。

这已被记录许多次已在StackOverflow中。请搜索以查找示例代码和进一步讨论。


关于java.time

java.time框架是建立在Java 8和更高版本。这些类取代了日期时间类legacy,如java.util.Date,Calendar,& SimpleDateFormat

Joda-Time项目现在位于maintenance mode,建议迁移到java.time。请参阅Oracle Tutorial。并搜索堆栈溢出了很多例子和解释。规格是JSR 310

从何处获取java.time类?

ThreeTen-Extra项目与其他类扩展java.time。这个项目是未来可能增加java.time的一个试验场。您可以在这里找到一些有用的类,如Interval,YearWeek,YearQuartermore

3

需要两个格式化如下

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));