Reputation: 574
I am writing a code to get current date of British Summer Time. I am stuck in converting the date in desired format using below code.
ZoneId zid = ZoneId.of("Europe/London");
ZonedDateTime lt = ZonedDateTime.now(zid);
// create a formatter
DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE;
// apply format()
String value = lt.format(formatter);
System.out.println("value ="+value);
I am getting the output as value =2020-06-01+02:00 which is fine as per written code. But I want output of format 01-JUN-20
What formatter shall I use to achieve this? Also will 'Europe/London' give proper date while in DST & also while not in DST? please help me in above 2 questions.
Upvotes: 1
Views: 1501
Reputation: 340098
ZonedDateTime
.now(
ZoneId.of( "Europe/London" )
)
.format(
DateTimeFormatter
.ofPattern( "dd-MMM-uu" )
.withLocale( Locale.UK )
)
.toUpperCase(
Locale.UK
)
See this code run live at IdeOne.com.
01-JUN-20
You asked:
will 'Europe/London' give proper date while in DST & also while not in DST?
Yes, your code is correct. Passing a ZoneId
to ZonedDateTime.now
does account for any anomalies in wall-clock time, including the anomaly of Daylight Saving Time (DST). The result is a date and time-of-day as seen by people in that region when they look up at the calendar & clock on their respective wall.
You may find it interesting or useful to see that same moment in UTC, an offset from UTC of zero hours-minutes-seconds. Extract a Instant
object by calling toInstant
.
You said:
But I want output of format 01-JUN-20
Define a custom formatting pattern to match your desired output. Instantiate a DateTimeFormatter
object.
Specify a Locale
object to determine the human language and cultural norms in naming and abbreviating the month name.
Locale locale = Locale.UK ; // Or Locale.US, etc.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MMM-uu" ).withLocale( locale ) ;
String output = myZonedDateTime.format( f ) ;
I do not know how to force all-uppercase in a DateTimeFormatter
formatting pattern. Perhaps DateTimeFormatterBuilder
might help; I don't know. As a workaround, you could simply call String.toUpperCase( Locale )
.
Locale locale = Locale.US ; // Or Locale.UK, etc.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MMM-uu" ).withLocale( locale ) ;
String output = myZonedDateTime.format( f ).toUpperCase( locale ) ;
DateTimeFormatter.ofLocalizedDateTime
. Upvotes: 4