[英]How to convert String into Date object using “DateFormat”?
I am trying to convert the date/Time of my machine into GMT time zone by using the following code: 我正在尝试通过使用以下代码将计算机的日期/时间转换为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));
Above code output : 上面的代码输出:
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
However my problem when I parse the " Converted Date As String " to " Converted Date As date object " by using the parse function, but as you can notice that the date changes to the original date 但是,当我通过使用parse函数将“转换为字符串形式的日期”解析为“转换为日期对象的日期对象”时出现问题,但是您会注意到该日期更改为原始日期
Why is that happen ? 为什么会这样呢?
The problem is solve, when I do the following : 当我执行以下操作时,问题就解决了:
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));
I am wondering why thats happen >> How the Local format related to parse Function ? 我想知道为什么会这样>>本地格式如何与解析函数相关? Does any one know why?
有谁知道为什么吗?
The return value from DateFormat.parse(String)
is a java.util.Date
, which does not retain any information about time zone or locale. DateFormat.parse(String)
的返回值是java.util.Date
,它不保留有关时区或语言环境的任何信息。 A Date
is essentially a wrapper object around a long
value representing a number of milliseconds since January 1, 1970 at 00:00 GMT. Date
本质上是围绕long
值的包装对象,该long
值表示自格林尼治标准时间1970年1月1日以来的毫秒数。 When its toString()
method is invoked, the default implementation renders the date in your local system's default timezone. 调用其
toString()
方法时,默认实现将在本地系统的默认时区中呈现日期。
If you want to create a date/time representation which stores both a timestamp and an associated time zone / locale, you should create a java.util.Calendar
object (using Calendar.getInstance(...)
and provide it with a TimeZone
and/or a Locale
, then set the time associated with the calendar with the Date
object representing the date/time you want. 如果要创建同时存储时间戳和关联的时区/地区的日期/时间表示,则应创建一个
java.util.Calendar
对象(使用Calendar.getInstance(...)
并为其提供TimeZone
和/或Locale
,然后使用Date
对象设置与日历关联的时间,该对象代表所需的日期/时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.