0

I'm trying to format the current date with DateTimeFormatter and I almost get what I need, but my problem seems to be that days of the week are enumerated from Sunday, instead of Monday. So, for example, if I run below code on Tuesday

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter;
final LocalDateTime currentTime = LocalDateTime.now()
def DATE = currentTime.format(DateTimeFormatter.ofPattern("YYYY'cw'w'd'e"))

I'd expect the output: 2020cw10d2, but the actual output I get is 2020cw10d3. There's a localized day of week pattern in DateTimeFormatter documentation, which is e/c option, however, it doesn't seem to change anything in my case. I'm located in Europe (GMT+1) and weeks are enumerated from Monday. Servers I work with are also located in the same timezone, but still, I get the same output on my desktop and my servers. What am I doing wrong? Is there a way to enumerate weeks from Monday in DateTimeFormatter?

G.M
  • 653
  • 1
  • 15
  • 35

1 Answers1

2

You can give the DateTimeFormatter a locale with withLocale:

currentTime.format(DateTimeFormatter.ofPattern("YYYY'cw'w'd'e").withLocale(Locale.UK));

Or pass it as a second parameter to ofPattern:

currentTime.format(DateTimeFormatter.ofPattern("YYYY'cw'w'd'e", Locale.UK));

However, the formatter should by default use your own locale though, so it's weird that it does something that you don't expect.

The UK locale counts week days starting from Monday, so you can use that instead, if you only wants to format weekdays in this specific way.

Sweeper
  • 213,210
  • 22
  • 193
  • 313