在Java中将日期格式dd-MM-yyyy更改为yyyy-MM-dd [英] Change date format dd-MM-yyyy to yyyy-MM-dd in Java

查看:409
本文介绍了在Java中将日期格式dd-MM-yyyy更改为yyyy-MM-dd的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将日期字符串08-12-2017转换为2017-12-08(LocalDate)。这是我尝试过的-

I was trying to convert date string 08-12-2017 to 2017-12-08(LocalDate). Here is what I tried-

    String startDateString = "08-12-2017";
    LocalDate date = LocalDate.parse(startDateString);
    System.out.println(date);

也尝试使用格式化程序,但得到相同的结果,即DateTimeParseException。
如何获得类似2017-12-08的输出,而不会出现异常?

Also tried using formatter, but getting same result, an DateTimeParseException. How can I get an output like 2017-12-08, without getting an exception?

推荐答案

尝试一下(

try {
    String startDateString = "08-12-2017";
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
    System.out.println(sdf2.format(sdf.parse(startDateString)));
} catch (ParseException e) {
    e.printStackTrace();
}

更新-Java 8

    String startDateString = "08-12-2017";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
    DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    System.out.println(LocalDate.parse(startDateString, formatter).format(formatter2));

这篇关于在Java中将日期格式dd-MM-yyyy更改为yyyy-MM-dd的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆