我正在使用groovy(确切地说是gremlin遍历图形数据库)。不幸的是,因为我使用的是 gremlin,所以我无法导入新类。
我有一些日期值,我希望将其转换为Unix时间戳。它们以 UTC 格式存储:2012-11-13 14:00:00:000
我正在使用这个片段(时髦)解析它:
def newdate = new Date().parse("yyyy-M-d H:m:s:S", '2012-11-13 14:00:00:000')
问题是它进行了时区转换,这会导致:
Tue Nov 13 14:00:00 EST 2012
如果我随后使用 time()
将其转换为时间戳,则会转换为 UTC,然后生成时间戳。
如何让new Date()
在首次解析日期时不进行任何时区转换(并假设日期为 UTC)?
以下是在 Java 中执行此操作的两种方法:
/*
* Add the TimeZone info to the end of the date:
*/
String dateString = "2012-11-13 14:00:00:000";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d H:m:s:S Z");
Date theDate = sdf.parse(dateString + " UTC");
/*
* Use SimpleDateFormat.setTimeZone()
*/
String dateString = "2012-11-13 14:00:00:000";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d H:m:s:S");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date theDate = sdf.parse(dateString);
请注意,Date.parse() 已被弃用(所以我不推荐它)。
我使用日历来避免时区转换。虽然我没有使用新的 Date(),但结果是一样的。
String dateString = "2012-11-13 14:00:00:000";
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d H:m:s:S");
calendar.setTime(sdf.parse(dateString));
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = calendar.getTime();
日期类解析(字符串 str) 从 JDK 1.1 中弃用,请尝试也支持时区和区域设置的 SimpleDateFormat 类。