[英]Convert a timestamp EEE, d MMM yyyy HH:mm:ss GMT format to yyyy-MM-dd'T'HH:mm:ss'Z' format?
I want to convert the timestamp Wed, 20 Feb 2013 11:41:23 GMT
to 2013-02-20T11:41:23Z
. 我想将时间戳为Wed, 20 Feb 2013 11:41:23 GMT
转换为2013-02-20T11:41:23Z
。 How can I do this? 我怎样才能做到这一点? I want to ISO-8601 in UTC format(2013-20-02T04:51:03Z). 我想要UTC格式的ISO-8601(2013-20-02T04:51:03Z)。
My code is below 我的代码如下
Date date=new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
String strDate = date.toString();
Date dt = formatter.parse(strDate );
System.out.println("Date " +dt);
Output is: 输出为:
Exception in thread "main" java.text.ParseException: Unparseable date: "Wed Feb 20 03:50:03 PST 2013"
Its your format what is wrong, use: "EEE MMM dd HH:mm:ss Z yyyy" that is what is comming out of the exception, in the question you have "EEE, dd MMM yyyy HH:mm:ss Z" for Wed, 20 Feb 2013 11:41:23 GMT 其格式错误,请使用: “ EEE MMM dd HH:mm:ss Z yyyy”这是一个例外,在问题中您有“ EEE,dd MMM yyyy HH:mm:ss Z” 2013年2月20日,星期三,格林尼治标准时间
Try: 尝试:
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat(
"EEE MMM dd HH:mm:ss Z yyyy");
String strDate = date.toString();
Date dt = null;
try {
dt = formatter.parse("Wed Feb 20 03:50:03 PST 2013");
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("Date " + dt);
System.out.println(new Timestamp(new Date().getTime()));
考虑使用Joda Time ,它内置了对解析和输出ISO格式日期字符串的支持。
new DateTime(DateTimeZone.UTC).toString()
You need 2 DateFormatters, one for parsing and one for output. 您需要2个DateFormatter,一个用于解析,另一个用于输出。 You have the one for output. 您有一个要输出。
EDIT: Output works like this: 编辑:输出是这样的:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
String output = formatter.format(new Date());
System.out.println("Date " + output);
DateFormat format = new SimpleDateFormat ("yyyy-MM-dd'T'HH:mm:ss'Z'");
format.setTimeZone (TimeZone.getTimeZone ("UTC"));
Date date = new Date ();
System.out.println ("Date is: " + format.format (date));
You already have a Date
object. 您已经有一个Date
对象。 You just need to format
it to String
. 您只需要将其format
为String
。
formatter.format(date)
should give you the desired result if the pattern in the SimpleDateFormat
constructor is valid. 如果SimpleDateFormat
构造函数中的模式有效,则formatter.format(date)
应该会为您提供所需的结果。
With the above implementation your code looks like this: 通过上述实现,您的代码如下所示:
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
String dt = formatter.format(date);
System.out.println("Date " + dt);
Which results in an output like - Date 2013-02-20T17:39:45Z
. 结果为Date 2013-02-20T17:39:45Z
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.