问题
I have date strings being created with different timezones, and I need to display them in a different format, but still showing each one's original timezone.
I'm able to parse, but it parses to a unix timestamp, which then loses the original timezone.
def dateCreated = issue.fields.created
// 2018-12-21T10:20:00.483-0800
def dateParsed = Date.parse("yyyy-MM-dd'T'HH:mm:ss.SSSz", dateCreated)
// 1545416400483
def dateFormatted = dateParsed.format('yyyy-MM-dd h:mm a, z')
// 2018-12-21 6:20 PM, UTC
Is there a way to parse/format straight to the desired format without losing the timezone in the middle?
回答1:
in java8 there are new classes to parse/format datetime:
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
def dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX")
ZonedDateTime zdt = ZonedDateTime.parse('2018-12-21T10:20:00.483-0800',dtf)
println zdt.getZone()
and starting from groovy 2.5 this code could be minimized to
ZonedDateTime zdt = ZonedDateTime.parse('2018-12-21T10:20:00.483-0800',"yyyy-MM-dd'T'HH:mm:ss.SSSX")
println zdt.getZone()
回答2:
Okay, I realized that this wouldn't actually get me what I want. The original string uses -0800
, which is an offset, not a timezone. So I looked elsewhere in the API response and found the timezone of the person who created the issue. I used this to format the date properly.
Final code:
def dateCreated = issue.fields.created
// 2018-12-21T10:20:00.483-0800
def creatorTimeZone = issue.fields.creator.timeZone
// America/Los_Angeles
def dateParsed = Date.parse("yyyy-MM-dd'T'HH:mm:ss.SSSz", dateCreated)
// 1545416400483
def dateFormatted = dateParsed.format('yyyy-MM-dd h:mm a, z', TimeZone.getTimeZone(creatorTimeZone))
// 2018-12-21 10:20 AM, PST
来源:https://stackoverflow.com/questions/53948091/parse-date-string-without-losing-timezone-in-groovy-for-jira