-3

I have a date in a String:

String string = "16.03.2017, 09:22";

I'm trying to convert it to a Date.

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

No matter what value I give to this function, it prints date "Mon Dec 26 09:22:00 MSK 2016". The time value is current, but the date is always the same.

How is this caused and how can I solve it?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555

3 Answers3

1

Your date format is incorrect. Use this line to replace the one in your code:

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

Full code:

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

Hope this helps!

anacron
  • 6,443
  • 2
  • 26
  • 31
0

Your formatting pattern is incorrect. The codes used are case-sensitive. The dd and yyyy should be lowercase.

Also you are ignoring the crucial issue of time zone.

And you are using the troublesome old legacy date-time classes such as Date and SimpleDateFormat. Use the modern java.time classes instead. Hundreds of existing Questions and Answers on Stack Overflow on this topic. Search for class names ZoneId, LocalDateTime, ZonedDateTime, and DateTimeFormatter.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd.MM.uuuu, HH:mm" );
LocalDateTime ldt = LocalDateTime.parse(  "16.03.2017, 09:22" , f );
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

Just Change the format in SimpleDateFormat cunstructor. You have used a wrong formatter DD.MM.YYYY, HH:mm. So just replace it with "dd.MM.yyyy, HH:mm"

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