如何在java中转换日期 [英] how to convert date in java

查看:88
本文介绍了如何在java中转换日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Android中是新的。
我必须将以下日期转换成这个时间戳( Wed Oct 12 14:17:42 GMT + 05:30 2011

 星期四,2010年5月27日12:37:27 GMT 

这是从服务器通过标题获取的日期。我已将其转换为String对象。现在我必须将它转换成日期格式,如: Wed Oct 12 14:17:42 GMT + 05:30 2011



请你帮帮我怎么把这个格式转换成使用时间戳的格式( Wed Oct 12 14:17:42 GMT + 05:30 2011 )。

解决方案

看看 DateFormat 提供 parse() format()方法的SimpleDateFormat DateFormat 提供了一堆标准格式,而 SimpleDateFormat 允许您提供自己的格式表达式。



输入日期的示例:

  //请注意,您还需要语言环境,由于工作日和月份是用特定的语言编写的,所以在这种情况下的英语
SimpleDateFormat parseFormat = new SimpleDateFormat(E,dd MMM yyyy HH:mm:ss z,Locale.ENGLISH);
SimpleDateFormat writeFormat = new SimpleDateFormat(E MMM dd HH:mm:ss z yyyy,Locale.ENGLISH);
writeFormat.setTimeZone(TimeZone.getTimeZone(GMT));

日期tDate = parseFormat.parse(Wed,12 Oct 2011 14:17:42 GMT);

System.out.println(writeFormat.format(tDate)); // Wed Oct 12 14:17:42 GMT 2011

编辑:如果你想要一个更多的可用API ,请尝试 JodaTime


I am new in android . I have to convert following date into this time stamp (Wed Oct 12 14:17:42 GMT+05:30 2011)

Thu, 27 May 2010 12:37:27 GMT

This is the date that I am getting from the server through the header. I have converted it into the String object. Now I have to convert it into the Date format like: Wed Oct 12 14:17:42 GMT+05:30 2011

Please could you help me how should I convert it into the (Wed Oct 12 14:17:42 GMT+05:30 2011) this format using timestamp.

解决方案

Have a look at DateFormat or SimpleDateFormat which provide parse() and format() methods. DateFormat provides a bunch of standard formats whereas SimpleDateFormat allows you to provide your own format expression.

Example for your input date:

//note that you need the locale as well, since the weekdays and months are written in a specific language, English in that case
SimpleDateFormat parseFormat = new SimpleDateFormat( "E, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH );
SimpleDateFormat writeFormat = new SimpleDateFormat( "E MMM dd HH:mm:ss z yyyy", Locale.ENGLISH );
writeFormat.setTimeZone( TimeZone.getTimeZone( "GMT" ) );

Date tDate = parseFormat.parse( "Wed, 12 Oct 2011 14:17:42 GMT" );

System.out.println(writeFormat.format(tDate )); //Wed Oct 12 14:17:42 GMT 2011

Edit: If you want a more usable API, try JodaTime.

这篇关于如何在java中转换日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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