以Java格式获取UTC格式的日期对象
问题描述:
我写了以下代码。我想以UTC格式获取Date对象。
I have written following code. I want to get Date object in UTC format.
我能够使用 SimpleDateFormat
获得UTC中的预期日期字符串。但是使用相同的 SimpleDateFormat
对象,我无法以UTC格式获取对象。它返回IST格式的对象。
I am able to get expected date string in UTC using SimpleDateFormat
. But using same SimpleDateFormat
object, I am not able to get object in UTC format. It is returning object with IST format.
搜索后,我发现Date对象不存储时间戳信息。
After searching, I found that Date object doesn't store timestamp info.
如何以UTC格式获取日期对象?
How can I get date object in UTC format ?
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class dddd {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Input - "+1393572325000L);
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date= new Date(1393572325000L);
String dateString = formatter.format(date);
System.out.println("Converted UTC TIME (using Format method) : "+dateString);
Date date2 =null;
try {
date2 = formatter.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("Parsed Date Object (using Parse method) : "+date2);
System.out.println("Expected Date Object : Fri Feb 28 07:25:25 UTC 2014");
}
}
这打印如下输出:
Input - 1393572325000
Converted UTC TIME (using Format method) : 2014-02-28 07:25:25
Parsed Date Object (using Parse method) : Fri Feb 28 12:55:25 IST 2014
Expected Date Object : Fri Feb 28 07:25:25 UTC 2014
答
final Date currentTime = new Date();
final SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, yyyy hh:mm:ss a z");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("UTC time: " + sdf.format(currentTime));