java 用 T 字符格式化特定日期

java format particular date with T character

解析此日期的正确格式是什么?:2015-05-29T00:00:00+02:00

DateFormat format = new SimpleDateFormat("yyyyy-mm-dd hh:mm:ss");
Date data = format.parse(dataValue);

试试

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");

注意

  • MM 代表月份,而 mm 代表分钟。
  • 如果你想要 24 小时格式使用 HHhh 用于 12 小时格式
  • XXX 表示时区格式如 -08:00
  • 要在格式中添加像 T 这样的文字,您需要用单引号 ' 将其括起来,例如 'T'

java.time

旧版日期时间 API(java.util 日期时间类型及其格式 API、SimpleDateFormat)已过时且容易出错。建议完全停止使用,改用java.time,即modern date-time API*.

由于现代日期时间 API 基于 ISO 8601 standards, you are not required to use a DateTimeFormatter object explicitly to parse a date-time string conforming to the ISO 8601 standards. Your date-time string contains timezone offset string (+02:00) and therefore, the most appropriate type to be used to parse it is OffsetDateTime

演示:

import java.time.OffsetDateTime;

public class Main {
    public static void main(String args[]) {
        OffsetDateTime odt = OffsetDateTime.parse("2015-05-29T00:00:00+02:00");
        System.out.println(odt);
    }
}

输出:

2015-05-29T00:00+02:00

无论出于何种原因,如果您需要来自 OffsetDateTime 对象的 java.util.Date 实例,您可以按如下方式进行:

Date date = Date.from(odt.toInstant());

Trail: Date Time[=52= 中了解有关 modern date-time API* 的更多信息].


* 无论出于何种原因,如果您必须坚持Java 6 或Java 7,您可以使用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