当我创建一个新的Date对象时,它被初始化为当前时间,但在本地时区。如何获得当前的GMT日期和时间?
当前回答
如果你正在使用joda time,并希望当前时间以毫秒为单位,不需要本地偏移量,你可以使用这个:
long instant = DateTimeZone.UTC.getMillisKeepLocal(DateTimeZone.getDefault(), System.currentTimeMillis());
其他回答
转换UTC当前日期时间:
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
DateTimeZone dateTimeZone = DateTimeZone.getDefault(); //Default Time Zone
DateTime currDateTime = new DateTime(); //Current DateTime
long utcTime = dateTimeZone.convertLocalToUTC(currDateTime .getMillis(), false);
String currTime = formatter.print(utcTime); //UTC time converted to string from long in format of formatter
currDateTime = formatter.parseDateTime(currTime); //Converted to DateTime in UTC
其实不是时间,而是它的表现形式可以改变。
SimpleDateFormat f = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
f.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(f.format(new Date()));
地球上任何地方的时间都是一样的,但我们对时间的感知可能会因地点的不同而不同。
如果你想要一个Date对象,字段调整为UTC,你可以用Joda Time这样做:
import org.joda.time.DateTimeZone;
import java.util.Date;
...
Date local = new Date();
System.out.println("Local: " + local);
DateTimeZone zone = DateTimeZone.getDefault();
long utc = zone.convertLocalToUTC(local.getTime(), false);
System.out.println("UTC: " + new Date(utc));
:
Calendar cal = Calendar.getInstance();
然后就可以得到当前的日期和时间。 您还可以获得当前日期和时间的时区:
Calendar cal2 = Calendar.getInstance(TimeZone.getTimeZone("GMT-2"));
你可以问cal.get(Calendar.DATE);或其他日历常量关于其他细节。 日期和时间戳在Java中已弃用。它不是日历类。
当我需要输出一个Date对象时,这就是我这样做的方式,通常情况下,您需要在SQL数据库中保存一个日期,而我希望它是UTC。我只是减去当地时区的偏移时间。
ZonedDateTime now = ZonedDateTime.now();
Date nowUTC = new Date(1000 * (now.toEpochSecond() - now.getOffset().getTotalSeconds()));
- - -更新 巴兹尔建议用一种更清洁的方式来达到同样的效果
Date nowUTC = Date.from(ZonedDateTime.now().toInstant());
但是在非utc java系统环境中测试后,我看到结果并不相同。根据巴兹尔的代码,日期仍然在本地区域
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 为什么Chrome浏览器不正确地确定页面是在不同的语言,并提供翻译?
- 解析日期字符串并更改格式
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?