iso8601 转换 java_将符合ISO 8601的字符串转换为java.util.Date

好的,这个问题已经回答了,但无论如何我都会放弃我的答案。它可能对某人有帮助。

我一直在寻找Android(API 7)的解决方案。Joda是不可能的 - 它是巨大的,并且缓慢初始化。对于这一特定目的而言,这似乎也是一种重大的过度杀伤力

涉及的答案javax.xml将无法在Android API 7上运行。

结束了实现这个简单的类。它仅涵盖最常见的ISO 8601字符串形式,但在某些情况下这应该足够了(当您确定输入将采用此格式时)。import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.

GregorianCalendar;/**

* Helper class for handling a most common subset of ISO 8601 strings

* (in the following format: "2008-03-01T13:00:00+01:00"). It supports

* parsing the "Z" timezone, but many other less-used features are

* missing.

*/public final class ISO8601 {

/** Transform Calendar to ISO 8601 string. */

public static String fromCalendar(final Calendar calendar) {

Date date = calendar.getTime();

String formatted = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")

.format(date);

return formatted.substring(0, 22) + ":" + formatted.substring(22);

}

/** Get current date and time formatted as ISO 8601 string. */

public static String now() {

return fromCalendar(GregorianCalendar.getInstance());

}

/** Transform ISO 8601 string to Calendar. */

public static Calendar toCalendar(final String iso8601string)

throws ParseException {

Calendar calendar = GregorianCalendar.getInstance();

String s = iso8601string.replace("Z", "+00:00");

try {

s = s.substring(0, 22) + s.substring(23);  // to get rid of the ":"

} catch (IndexOutOfBoundsException e) {

throw new ParseException("Invalid length", 0);

}

Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(s);

calendar.setTime(date);

return calendar;

}}

性能说明:我每次都会实例化新的SimpleDateFormat,以避免Android 2.1中的错误。如果你像我一样惊讶,看到这个谜语。对于其他Java引擎,您可以将实例缓存在私有静态字段中(使用ThreadLocal,以保证线程安全)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值