ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java – 如何在解析日期时保留时区?

2019-06-25 08:48:10  阅读:320  来源: 互联网

标签:java jodatime datetimeoffset


我解析了时区信息的日期,比如:1/7/2008 11:00:00 AM -0700. -0700对应于加利福尼亚州的当前时间偏移,因为我们现在在PDT.如果我解析它并显示:

org.joda.time.format.DateTimeFormat.forPattern("M/d/yyyy hh:mm:ss a Z")
    .parseDateTime("1/7/2008 11:00:00 AM -0700").toString()

我得到:2008-01-07T10:00:00.000-08:00.这是“正确的”,如上午10点-0800 =上午11点-0700,但我如何得到返回的日期以保持输入中的相同时间偏移(Z部分)?

作为旁注,使用java.text.SimpleDateFormat给出了类似的结果:new SimpleDateFormat(“M / d / yyyy hh:mm:ss a Z”).parse(“1/7/2008 11:00:00 AM – 0700“).toString()返回2011年1月7日10:00:00 PST 2008,PST = -0800,而我们现在在PDT.

解决方法:

您提供的日期是一月份,而不是白天.因此,如果您将这些时间视为太平洋时间,则-0800偏移是正确的.

但你没有指定像America / Los_Angeles这样的时区ID,那么为什么JodaTime会做出这样的假设呢?

对于DateTimeFormatter类,可以在the documentation中找到答案:

The underlying printer/parser can be altered to behave exactly as
required by using one of the decorator modifiers:

withLocale(Locale) – returns a new formatter that uses the specified locale
withZone(DateTimeZone) – returns a new formatter that uses the specified time zone
withChronology(Chronology) – returns a new formatter that uses the specified chronology
withOffsetParsed() – returns a new formatter that returns the parsed time zone offset
withPivotYear() – returns a new formatter with the specified pivot year
withDefaultYear() – returns a new formatter with the specified default year

The documentation为DateTimeFormatter.forPattern()方法说:

The format may contain locale specific output, and this will change as you change the locale of the formatter. Call DateTimeFormatter.withLocale(Locale) to switch the locale.

由于您不想使用特定的区域设置或时区,我相信您应该使用以下内容:

org.joda.time.format.DateTimeFormat.forPattern("M/d/yyyy hh:mm:ss a Z")
        .withOffsetParsed()
        .parseDateTime("1/7/2008 11:00:00 AM -0700").toString()

有关.withOffsetParsed()的行为,请参阅these docs,这正是您所询问的内容.

标签:java,jodatime,datetimeoffset
来源: https://codeday.me/bug/20190625/1284451.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有