Parse date string without losing timezone in Groovy for Jira

半腔热情 提交于 2021-01-29 07:22:41

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!