设置 XML 日期格式以包含 UTC 偏移量

发布于 2024-11-14 19:44:52 字数 892 浏览 3 评论 0原文

我正在生成一个 XML,其中包含有效 XML 格式的日期,并且我还需要它包含 UTC 偏移量。

我正在使用 groovy 但我会显示我正在使用的 Java 代码(任何一种语言的答案都很好):

Calendar c = Calendar.getInstance();  
long timeZoneOffset = c.timeZone.getOffset(c.getTimeInMillis())/(1000*60*60);
SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
formatter.format(c.getTime()) + "+0" + timeZoneOffset + ":00";

上面的代码给了我 2011-06-12T07:23:25.000+03:00,但是这段代码有两个问题:

  1. 它很丑陋,而且可能不是最好的方法
  2. 它不适用于像这样的时区印度 (GMT +5:30)、尼泊尔 (GMT +5:45)

我尝试使用 new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss Z") 用于时区,但它给了我2011-06-12T07:23:25.000+0300 这不是正确的格式(+0300 而不是 +03:00)。

还有其他方法可以按照我需要的方式格式化日期吗? (最好没有第三方)

I'm generating an XML which contains a date in a valid XML format, and I need it to include a UTC offset as well.

I'm ussing groovy but I'll show the Java code I'm using instead (an answer in either language is good):

Calendar c = Calendar.getInstance();  
long timeZoneOffset = c.timeZone.getOffset(c.getTimeInMillis())/(1000*60*60);
SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
formatter.format(c.getTime()) + "+0" + timeZoneOffset + ":00";

The above code give4s me 2011-06-12T07:23:25.000+03:00, but this code has two problems:

  1. It is ugly, and probably not the best way to do this
  2. It won't work for timezones like India (GMT +5:30), Nepal (GMT +5:45)

I tried using new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss Z") for the timezone, but it gave me 2011-06-12T07:23:25.000+0300 which is not a correct format (+0300 instead of +03:00).

Any other way to format the date the way I need it? (preferably without 3rd parties)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

指尖微凉心微凉 2024-11-21 19:44:52

另一种选择 - 也埋在 jaxb api 中 - (不需要 Jodatime):

    Calendar c = ...
    String printDate = javax.xml.bind.DatatypeConverter.printDateTime(c);

HTH

One other alternative - also buried inside jaxb api - (not needing Jodatime):

    Calendar c = ...
    String printDate = javax.xml.bind.DatatypeConverter.printDateTime(c);

HTH

一笑百媚生 2024-11-21 19:44:52

我认为最优雅的方法是使用 Joda-Time 库。您需要 ISO 8601(第 5.4 节)格式(由 xs:dateTime XSD 类型表示):

 DateTime dt = new DateTime();
 DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
 System.out.println(fmt.print(dt));

结果:

2011-06-12T07:36:32.294+02:00

I think that most elegant way is to use Joda-Time library. You need ISO 8601 (Section 5.4) format (as represented by xs:dateTime XSD type):

 DateTime dt = new DateTime();
 DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
 System.out.println(fmt.print(dt));

Result:

2011-06-12T07:36:32.294+02:00

葬心 2024-11-21 19:44:52

您是否尝试过使用 XMLGregorianCalendar?例如:

Calendar c = ...
DataTypeFactory f = DataTypeFactory.newInstance();
XMLGregorianCalendar xc = f.newXMLGregorianCalendar(c);
String str = xc.toXMLFormat();

如果日历是带有时区偏移的日期时间,则时区偏移应包含在按照 XML 数据类型规范格式化的结果字符串中。

Have you tried using XMLGregorianCalendar? For example:

Calendar c = ...
DataTypeFactory f = DataTypeFactory.newInstance();
XMLGregorianCalendar xc = f.newXMLGregorianCalendar(c);
String str = xc.toXMLFormat();

If the calendar is a date-time with a timezone offset, then the timezone offset should be included in the result String formatted as per the XML Datatypes specification.

娇女薄笑 2024-11-21 19:44:52

SimpleDataFormat http://docs.oracle.com/javase/ 7/docs/api/java/text/SimpleDateFormat.html
支持格式说明符字母 X,其中包含时区中的冒号“:”。值得阅读有关时区的部分,特别是有关“ThreeLetterISO8601TimeZone”的部分,

使用格式字符串“yyyy.MM.dd HH:mm:ss.sssXXX”给了我 2015.05.07 15:06:58.058+10:00

SimpleDataFormat http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
supports a format specifier letter of X which includes the colon ":" in the time zone. Its worth reading the sectiona about time zones and in particular the part about "ThreeLetterISO8601TimeZone"

Using the format string "yyyy.MM.dd HH:mm:ss.sssXXX" gave me 2015.05.07 15:06:58.058+10:00

对你的占有欲 2024-11-21 19:44:52

java.time

现代date-time API* 不仅使其易于实现,而且解决方案看起来也清晰自然。

演示:

import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        ZonedDateTime zdtNewYork = ZonedDateTime.now(ZoneId.of("America/New_York"));
        ZonedDateTime zdtIndia = ZonedDateTime.now(ZoneId.of("Asia/Kolkata"));
        ZonedDateTime zdtNepal = ZonedDateTime.now(ZoneId.of("Asia/Kathmandu"));
        System.out.println(zdtNewYork);
        System.out.println(zdtIndia);
        System.out.println(zdtNepal);

        // If you do not need to display the time zone name, convert it into
        // OffsetDateTime
        OffsetDateTime odtNewYork = zdtNewYork.toOffsetDateTime();
        System.out.println(odtNewYork);

        // Using DateTimeFormatter, you can display it in different formats
        String odtFormat = zdtNewYork.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME.withLocale(Locale.ENGLISH));
        String dayMonFullNameFormat = zdtNewYork.format(DateTimeFormatter.ofPattern("EEEE d MMMM uuuu HH:mm:ssXXX"));
        System.out.println(odtFormat);
        System.out.println(dayMonFullNameFormat);
    }
}

输出:

2021-05-09T16:41:23.683709-04:00[America/New_York]
2021-05-10T02:11:23.685131+05:30[Asia/Kolkata]
2021-05-10T02:26:23.685187+05:45[Asia/Kathmandu]
2021-05-09T16:41:23.683709-04:00
2021-05-09T16:41:23.683709-04:00
Sunday 9 May 2021 16:41:23-04:00

了解有关 现代日期时间 API* 来自 跟踪:日期时间


* 无论出于何种原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport 将大部分 java.time 功能向后移植到 Java 6 和 Java 6 7. 如果您正在处理 Android 项目,并且您的 Android API 级别仍然不符合 Java-8,请检查 通过脱糖提供 Java 8+ API如何在Android项目中使用ThreeTenABP

java.time

The modern date-time API* not only makes it easy to do but the solution also looks lucid and natural.

Demo:

import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        ZonedDateTime zdtNewYork = ZonedDateTime.now(ZoneId.of("America/New_York"));
        ZonedDateTime zdtIndia = ZonedDateTime.now(ZoneId.of("Asia/Kolkata"));
        ZonedDateTime zdtNepal = ZonedDateTime.now(ZoneId.of("Asia/Kathmandu"));
        System.out.println(zdtNewYork);
        System.out.println(zdtIndia);
        System.out.println(zdtNepal);

        // If you do not need to display the time zone name, convert it into
        // OffsetDateTime
        OffsetDateTime odtNewYork = zdtNewYork.toOffsetDateTime();
        System.out.println(odtNewYork);

        // Using DateTimeFormatter, you can display it in different formats
        String odtFormat = zdtNewYork.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME.withLocale(Locale.ENGLISH));
        String dayMonFullNameFormat = zdtNewYork.format(DateTimeFormatter.ofPattern("EEEE d MMMM uuuu HH:mm:ssXXX"));
        System.out.println(odtFormat);
        System.out.println(dayMonFullNameFormat);
    }
}

Output:

2021-05-09T16:41:23.683709-04:00[America/New_York]
2021-05-10T02:11:23.685131+05:30[Asia/Kolkata]
2021-05-10T02:26:23.685187+05:45[Asia/Kathmandu]
2021-05-09T16:41:23.683709-04:00
2021-05-09T16:41:23.683709-04:00
Sunday 9 May 2021 16:41:23-04:00

Learn more about the the modern date-time API* from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文