0

I have this groovy code which gives me an error and I cannot see why:

import java.text.SimpleDateFormat
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.time.temporal.TemporalAdjusters

static String convertDateTimeString(String fromFormat, String toFormat, String dateString) {
    DateTimeFormatter fromFormatter = DateTimeFormatter.ofPattern(fromFormat, Locale.GERMAN)
    LocalDateTime localDateTime = LocalDateTime.parse(dateString, fromFormatter)
    DateTimeFormatter toFormatter = DateTimeFormatter.ofPattern(toFormat, Locale.GERMAN)
    localDateTime.format(toFormatter)
}

String date = convertDateTimeString( 'EEE, dd MMM yyyy HH:mm:ss z', 'yyyy', "Wed, 04 Feb 2015 10:12:34 UTC")
assert date == '2015'

The error ist java.time.format.DateTimeParseException: Text 'Wed, 04 Feb 2015 10:12:34 UTC' could not be parsed at index 0

But I checked the JavaDocs and everything looks good to me.

Can you tell me what's the problem here?

Erando
  • 811
  • 3
  • 13
  • 27

2 Answers2

6

The problem is that you set the formatter to parse/format for Locale.GERMAN but gave it "Wed, 04 Feb 2015 10:12:34 UTC" to parse. Wed is for wednesday which is english, not german.

To solve the problem, just replace Locale.GERMAN by Locale.ENGLISH. Another solution would be a parameter for the locale.

akuzminykh
  • 4,522
  • 4
  • 15
  • 36
1

Instead of "Wed", we need to use short weekdays 'So, Mo, Di, Mi, Do, Fr, Sa' in German.

String date = convertDateTimeString( "EEE, dd MMM yyyy HH:mm:ss z", "yyyy", "Mi, 04 Feb 
2015 10:12:34 UTC");

// output 2015

Ravi Sharma
  • 160
  • 4