Java DateTimeFormatter start week with Monday Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Java DateTimeFormatter start week with Monday without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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?

Answer

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.

We are here to answer your question about Java DateTimeFormatter start week with Monday - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji