2017-02-28 71 views
-3

我有一个String日期:麻烦转换字符串到日期在Java中

String string = "16.03.2017, 09:22"; 

我试图将其转换为Date

Locale russianLocale = new Locale.Builder().setLanguage("ru").setRegion("RU").build(); 
Date date = new SimpleDateFormat("DD.MM.YYYY, HH:mm",russianLocale).parse(string); 

无论我给这个函数什么值,它都会打印日期“Mon Dec 26 09:22:00 MSK 2016”。时间值是最新的,但日期总是相同的。

这是如何造成的,我该如何解决?

回答

0

您的日期格式不正确。使用此行来替换你的代码的一个:

date = new SimpleDateFormat("dd.MM.yyyy, HH:mm", russianLocale).parse(string); 

全码:

private static Date convertStringToDate(String string) { 
    Date date = new Date(); 
    Locale russianLocale = new Locale.Builder().setLanguage("ru").setRegion("RU").build(); 
    try { 
     date = new SimpleDateFormat("dd.MM.yyyy, HH:mm", russianLocale).parse(string); 
    } catch (ParseException e) { 
     e.printStackTrace(); 
    } 
    return date; 
} 

希望这有助于!

0

您的格式模式不正确。使用的代码区分大小写。 ddyyyy应该是小写。

此外,你忽略了时区的关键问题。

而且您正在使用诸如DateSimpleDateFormat之类的麻烦的旧式遗留日期时间类。改用现代的java.time类。关于此主题的数百个关于堆栈溢出的现有问题和解答。搜索类名称ZoneId,LocalDateTime,ZonedDateTime和DateTimeFormatter。

DateTimeFormatter f = DateTimeFormatter.ofPattern("dd.MM.uuuu, HH:mm"); 
LocalDateTime ldt = LocalDateTime.parse( "16.03.2017, 09:22" , f); 
+0

是的,那是问题所在,谢谢 – theendcomplete

0

只需更改SimpleDateFormat cunstructor中的格式。您使用了错误的格式化程序DD.MM.YYYY,HH:mm。因此,只需将其替换为“dd.MM.yyyy,HH:mm”

private static Date convertStringToDate(String string){date:date Date = new Date(); Locale russianLocale = new Locale.Builder()。setLanguage(“ru”).setRegion(“RU”)。build(); 尝试date = new SimpleDateFormat(“dd.MM.yyyy,HH:mm”,russianLocale).parse(string); } catch(ParseException e){ e.printStackTrace(); } 返回日期; }