如何格式化给定的时间字符串并转换为日期/时间对象

时间:2015-06-20 09:12:59

标签: java date datetime datetime-format

我从休息服务中获取字符串形式的时间对象。我需要提取时间然后做一些时间操作。给定的时间字符串是“2015-06-16T14:58:48Z”。我尝试了下面的代码,将字符串转换为时间,但是得到的值不正确。

    String time = "2015-06-16T14:58:48Z";

    SimpleDateFormat formatter = new SimpleDateFormat("YYYY-MM-DD'T'hh:mm:ss'Z'", Locale.US);

    String dateInString = "2015-06-16T14:58:48Z";

    Date date = formatter.parse(dateInString);
    System.out.println("Original String : " + time);
    System.out.println("After converting to time : " + formatter.format(date));

我得到的输出如下: 原始字符串:2015-06-16T14:58:48Z 转换为时间后:2015-12-362T02:58:48Z

转换日期某种程度上是错误的值。请指出错误在哪里。谢谢。

3 个答案:

答案 0 :(得分:3)

将SimpleDateFormat更改为此..

SimpleDateFormat formatter = new SimpleDateFormat(
                "yyyy-MM-dd'T'HH:mm:ssX", Locale.US);

答案 1 :(得分:3)

格式化字符串有几个错误:

  • package jwt import( "fmt" "net/http" "github.com/gorilla/mux" "github.com/dgrijalva/jwt-go" "io/ioutil" ) var privateKey []byte var publicKey []byte func JSONWebTokensHandler(w http.ResponseWriter, r * http.Request){ // Create the token encodeToken := jwt.New(jwt.SigningMethodHS256) // Set some claims encodeToken.Claims["Latitude"] = "25.000" encodeToken.Claims["Longitude"] = "27.000" // Sign and get the complete encoded token as a string tokenString, err := encodeToken.SignedString(privateKey) decodeToken, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) } return publicKey,nil }) if decodeToken.Valid { fmt.Fprintf(w,"Lat: %s, Lng: %s",decodeToken.Claims["Latitude"],decodeToken.Claims["Longitude"]) } else { fmt.Fprintf(w,"Couldn't handle this token: %s", err) } } func init(){ privateKey,_ = ioutil.ReadFile("demo.rsa") publicKey,_ = ioutil.ReadFile("demo.rsa.pub") r := mux.NewRouter() r.HandleFunc("/jwt",JSONWebTokensHandler).Methods("GET") http.Handle("/", r) } 表示周年,而不是,即Y
  • y表示的日期。您应该使用D,这意味着的日期。
  • d表示一天中有12小时的记谱时间。由于您有h,因此应使用14来处理24小时制表示法。

总结一下:

H

答案 2 :(得分:0)

java.time

问题的根本原因是使用了错误的符号

  • Y(指定 week-based-year)而不是 y(指定 year-of-era
  • D(指定 day-of-year)而不是 d(指定 day-of-month)。立>
  • h(指定 clock-hour-of-am-pm)而不是 H(指定 hour-of-day ).

检查documentation页面 了解有关这些符号的更多信息。

另外,请注意旧的日期时间 API(java.util 日期时间类型及其格式 API,SimpleDateFormat)已经过时且容易出错。建议完全停止使用,改用java.timemodern date-time API*

使用现代 API 的解决方案:

现代日期时间 API 基于 ISO 8601,只要日期时间字符串符合 ISO 8601 标准,就不需要您明确使用 DateTimeFormatter 对象。您的日期时间字符串符合 ISO 8601 标准(或 OffsetDateTime#parse 使用的默认格式)。

import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        String strDateTime = "2015-06-16T14:58:48Z";
        OffsetDateTime odt = OffsetDateTime.parse(strDateTime);
        System.out.println(odt);

        // ########################Extract time information########################
        LocalTime time = odt.toLocalTime();

        // You can also get it as time.getHour()
        // Extract other units in a similar way
        int hour = odt.getHour();

        // Also using time.format(DateTimeFormatter.ofPattern("a", Locale.ENGLISH));
        String amPm = odt.format(DateTimeFormatter.ofPattern("h a", Locale.ENGLISH));

        System.out.println(time);
        System.out.println(hour);
        System.out.println(amPm);
    }
}

输出:

2015-06-16T14:58:48Z
14:58:48
14
2 PM

注意:

  1. 输出中的 Z 是零时区偏移的 timezone designator。它代表祖鲁语并指定 Etc/UTC 时区(时区偏移为 +00:00 小时)。
  2. 出于任何原因,如果您需要将 OffsetDateTime 的这个对象转换为 java.util.Date 的对象,您可以这样做:
    Date date = Date.from(odt.toInstant());

modern date-time API 中了解有关 Trail: Date Time* 的更多信息。


* 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 & 7. 如果您正在为 Android 项目工作并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project