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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:10:47  来源:igfitidea点击:

How to convert DateTime to Date

javadatetimejodatime

提问by user93796

How can I convert Dateto DateTimeand vice versa?

我该如何转换DateDateTime反之亦然?

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 DateTimeyou're talking about? If so, it will be

难道这Joda TimeDateTime你在说什么?如果是这样,它将是

dateTime.toDate()

回答by CloudyMarble

You can easily use the toDate()function which gets the date time as a java.util.Date:

您可以轻松使用toDate()获取日期时间的函数java.util.Date

Date date = MydateTime.toDate();

回答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();