简体   繁体   English

Java - 如何将此字符串转换为日期?

[英]Java - How to convert this string to date?

我从服务器收到这个,我不明白T和Z意味着什么, 2012-08-24T09:59:59Z将此字符串转换为Date对象的正确SimpleDateFormat模式是什么?

This is ISO 8601 Standard. 这是ISO 8601标准。 You may use 你可以用

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

to convert this. 转换这个。

RSS 2.0 format string EEE, dd MMM yyyy HH:mm:ss z   
Example: Tue, 28 Aug 2012 06:55:11 EDT

Atom (ISO 8601) format string  yyyy-MM-dd'T'HH:mm:ssz
Example:2012-08-28T06:55:11EDT

try {
            String str_date = "2012-08-24T09:59:59Z";
            DateFormat formatter;
            Date date;
            formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            date = (Date) formatter.parse(str_date);
            System.out.println("Today is " + date);
        } catch (ParseException e) {
            System.out.println("Exception :" + e);
        } 

The Z stands for Zulu (UTC) and this is the dateTime.tz format ( ISO-8601 ). Z代表Zulu(UTC),这是dateTime.tz格式( ISO-8601 )。 So, you should be able to do something like this: 所以,你应该能够做到这样的事情:

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

There is an example here: example 这里有一个例子: 例子

This is the ISO datetime format, see here , T is the time separator and Z is the zone designator for the zero UTC offset. 这是ISO日期时间格式,请参见此处 ,T是时间分隔符,Z是零UTC偏移的区域指示符。

There is a very similar, if not identical question here , see it to know how to convert this string to a Java DateTime object. 有一个非常相似,如果不相同的问题在这里 ,看看就知道如何将这个字符串转换成Java DateTime对象。

import org.joda.time.*;
import org.joda.time.format.*;

public class Test {
    public static void main(String[] args) {
        String text = "2012-08-24T09:59:59Z";
        DateTimeFormatter parser = ISODateTimeFormat.dateTime();
        DateTime dt = parser.parseDateTime(text);

        DateTimeFormatter formatter = DateTimeFormat.mediumDateTime();
        System.out.println(formatter.print(dt));
    }
}

or simply check that link str to date 或者只是检查链接str到目前为止

也许使用优秀的joda时间库将String转换为日期:

LocalDate myDate = new LocalDate("2012-08-28") // the constructor need an Object but is internally able to parse a String.
// First parse string in pattern "yyyy-MM-dd'T'HH:mm:ss'Z'" to date object.

String dateString1 = "2012-08-24T09:59:59Z";
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").parse(dateString1);

// Then format date object to string in pattern "MM/dd/yy 'at' h:mma".
String dateString2 = new SimpleDateFormat("MM/dd/yy 'at' h:mma").format(date);
System.out.println(dateString2); // 08/24/12 at 09:59AM

I think this might be useful to you. 我想这可能对你有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM