格式化日期字符串java [英] Format a date String java

查看:95
本文介绍了格式化日期字符串java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似这样的日期字符串:- 2014年10月31日星期五11:30:58 GMT + 05:30
我想将其转换为 2014-10-31T6:00:00 应该在添加偏移量之后。我该怎么办?

I have a date String like so :- Fri Oct 31 11:30:58 GMT+05:30 2014 I want to Convert it into 2014-10-31T6:00:00 which should be after adding the offset. How can I do it?

推荐答案

首先,您需要一个SimpleDateFormat,其模式与您输入的字符串相匹配: EEE MMM dd HH:mm:ss z yyyy 。看一下: SimpleDateFromat API

First you need a SimpleDateFormat with the pattern that matches your input String: "EEE MMM dd HH:mm:ss z yyyy". Take a look at: SimpleDateFromat API

    SimpleDateFormat in = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");

然后,您可以解析输入的String以获取相应的Date对象,如下所示:

Then you can parse the input String to get a corresponding Date object as follows:

    Date date = in.parse("Fri Oct 31 11:30:58 GMT+05:30 2014");

请注意,Date对象没有时区作为其状态的一部分。如果要以UTC打印日期,则需要另一个SimpleDateFormat来格式化和打印所需时区中的日期。

Note that Date objects does not have timezone as part of its state. If you want to print the Date in UTC then you need another SimpleDateFormat to format and print the date in your required timezone.

    SimpleDateFormat out = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    out.setTimeZone(TimeZone.getTimeZone("UTC"));
    out.format(date);   

示例: http://ideone.com/Wojec3

public static void main (String[] args) throws java.lang.Exception
{
    SimpleDateFormat in = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
    SimpleDateFormat out = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    out.setTimeZone(TimeZone.getTimeZone("UTC"));

    Date date = in.parse("Fri Oct 31 11:30:58 GMT+05:30 2014");

    System.out.println(out.format(date));
}

这篇关于格式化日期字符串java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆