I have date without Z because it always in UTC. I want to parse it into LocalDateTime with local time and vice versa
For example:
local timezone UTC+1
server date "2020-01-31 04:38:00" in UTC
formatted will be "2020-01-31 05:38:00"
and vice versa
local time "2020-01-31 05:38:00" in UTC+1
formatted time will be "2020-01-31 04:38:00"
I tried this
val formatter = DateTimeFormatter
.ofPattern(Type.API.formatter)
.withZone(localTimeZone)
LocalDateTime.parse(date, formatter).toString()
Parse your input as LocalDateTime
.
LocalDateTime ldt = LocalDateTime.parse( "2020-01-31 04:38:00".replace( " " , "T" ) ) ;
You claim to know for sure that the string represents a moment as seen in UTC, that is, with an offset-from-UTC of zero hours-minutes-seconds.
OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ) ;
If you want to adjust into a time zone, apply a ZoneId
to get a ZonedDateTime
object.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;
I do not know why you involved Locale
. The Locale
class has nothing to do with date-time values. A Locale
is only needed if you are localizing when generating text to represent your date-time value, to determine names of month or day-of-week, and issues of capitalization, punctuation, abbreviation, order of parts.
Locale locale = Locale.JAPAN ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( locale ) ;
String output = zdt.format( f ) ;
See this code run live at IdeOne.com.
Both odt
& zdt
represent the same moment, the same simultaneous point on the timeline, but differ in their wall-clock time. People in Tunisia set their clocks one hour ahead of UTC. So in zdt
we see the time-of-day as 5:38 rather than 4:38.
ldt.toString() = 2020-01-31T04:38
odt.toString() = 2020-01-31T04:38Z
zdt.toString() = 2020-01-31T05:38+01:00[Africa/Tunis]
output = 2020年1月31日金曜日 5時38分00秒 中央ヨーロッパ標準時