Java 如何将日期时间转换为日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1005596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert DateTime to Date
提问by user93796
How can I convert Date
to DateTime
and vice versa?
我该如何转换Date
,DateTime
反之亦然?
E.g.
例如
Date dt = new Date();
Now I want to covert this to DateTime
.
现在我想将其转换为DateTime
.
Also
还
DateTime dtim = new DateTime();
Now I want to convert it to Date.
现在我想将它转换为日期。
回答by akarnokd
I guess you convert it to UTC via Date.getTime(). And after that, use a constructor/setter on the other object.
我猜你通过 Date.getTime() 将它转换为 UTC。之后,在另一个对象上使用构造函数/setter。
回答by skaffman
Is this Joda Time
's DateTime
you're talking about? If so, it will be
难道这Joda Time
的DateTime
你在说什么?如果是这样,它将是
dateTime.toDate()
回答by CloudyMarble
回答by AJC
As skaffman said above
正如斯卡夫曼上面所说
dateTime.toDate()
should do the trick. But keep in mind that if the dateTime object had a different timezone than the user's current timezone, dateTime.toDate() will return the date object in user's timezone. ie
应该做的伎俩。但请记住,如果 dateTime 对象的时区与用户的当前时区不同,则 dateTime.toDate() 将返回用户时区中的日期对象。IE
DateTime newDate = new DateTime().toDateTime(DateTimeZone.forID("America/Los_Angeles"));
System.out.println(newDate);
System.out.println(newDate.toDate());
This will print
这将打印
2017-07-05T14:19:23.294-07:00
2017-07-05T14:19:23.294-07:00
Wed Jul 05 15:19:23 MDT 2017
2017 年 7 月 5 日星期三 15:19:23 MDT
as my system time is in MDT
因为我的系统时间在 MDT
回答by Charly Monzon
Transform to date
:
转换为date
:
dateTime.toDate()
Transform to DateTime
:
转换为DateTime
:
new DateTime(new Date())
回答by Thilo
If you want to convert a DateTime to Date without losing the timezone, convert DateTime to Joda LocalDateTime first.
如果您想在不丢失时区的情况下将 DateTime 转换为 Date,请先将 DateTime 转换为 Joda LocalDateTime。
DateTime dateTimeUtc = new DateTime(); //because my default timezone is UTC
DateTime dateTimeBerlin = dateTimeUtc.withZone(DateTimeZone.forID("Europe/Berlin"));
Date convertedDate = dateTimeBerlin.toLocalDateTime().toDate();