java如何使用“DateFormat”将字符串转换为日期对象?
我正在尝试使用以下代码将我的机器的日期/时间转换为GMT时区:
DateFormat gmtFormat = new SimpleDateFormat("E MMM dd HH:mm:ss 'GMT' yyyy");
TimeZone gmtTime = TimeZone.getTimeZone("GMT");
gmtFormat.setTimeZone(gmtTime);
System.out.println("Orginal Date : " + new Date());
String s= gmtFormat.format(new Date());
System.out.println("Converted Date As String: "+ s);
System.out.println("Converted Date As date object : " + gmtFormat.parse(s));
以上代码输出:
Orginal Date : Mon Apr 21 21:04:06 AST 2014
Converted Date As String: Mon Apr 21 18:04:06 GMT 2014
Converted Date As date object : Mon Apr 21 21:04:06 AST 2014
然而,当我使用parse函数将“转换的日期作为字符串”解析为“转换的日期作为日期对象”时,我遇到了一个问题,但是您可以注意到,日期更改为原始日期
为什么会这样
当我执行以下操作时,问题就解决了:
DateFormat gmtFormat = new SimpleDateFormat("E MMM dd HH:mm:ss 'GMT' yyyy");
TimeZone gmtTime = TimeZone.getTimeZone("GMT");
gmtFormat.setTimeZone(gmtTime);
System.out.println("Orginal Date : " + new Date());
String s= gmtFormat.format(new Date());
System.out.println("Converted Date As String: "+ s);
// Just I added Local Time Zone Formatand I use it to call parse instead of gmtFormat
DateFormat LocalFormat = new SimpleDateFormat("E MMM dd HH:mm:ss 'GMT' yyyy");
System.out.println("Converted Date As date object : " + LocalFormat.parse(s));
我想知道为什么会这样>>;本地格式如何与解析函数相关?有人知道为什么吗
# 1 楼答案
来自
DateFormat.parse(String)
的返回值是一个java.util.Date
,它不保留任何关于时区或地区的信息。Date
本质上是一个包装器对象,它围绕着一个long
值,该值表示自1970年1月1日00:00 GMT起的毫秒数。当调用其toString()
方法时,默认实现会在本地系统的默认时区中呈现日期如果要创建一个日期/时间表示形式,该表示形式同时存储时间戳和相关时区/区域设置,您应该创建一个
java.util.Calendar
对象(使用Calendar.getInstance(...)
),并为其提供一个TimeZone
和/或Locale
,然后使用表示所需日期/时间的Date
对象设置与日历关联的时间