如何将 java.util.Date 对象转换为 Calendar 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19329750/
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-12 16:10:19  来源:igfitidea点击:

How to convert java.util.Date objects into Calendar objects?

javadatecalendar

提问by Click Upvote

I'm using the PrettyTimejava library for a variety of date/time processing in my java app, such as converting MySQL format dates/datetime strings into java dates, or the vice versa.

我在我的 java 应用程序中使用PrettyTimejava 库进行各种日期/时间处理,例如将 MySQL 格式的日期/日期时间字符串转换为 java 日期,反之亦然。

However, I see that date.getYear(), date.getMonth(), etc, are all deprecated, and it says to use Calendar instead. But PrettyTime only returns its results as Date objects, and I see no way to convert the Date objects into calendar objects.

但是,我看到date.getYear(), date.getMonth()等都已弃用,它说要改用 Calendar。但是 PrettyTime 仅将其结果作为 Date 对象返回,我认为无法将 Date 对象转换为日历对象。

In the documentation for Calendar, the only mention I see of Dateis the method setTime(Date date), but the method name is ambigious, and the documentation is not clear on what calling this method would actually do. Obviously I can't just do calendar.set( date.getYear(), date.getMonth(), ..)etc, as those methods of Dateare deprecated.

Calendar的文档中,我看到的唯一提及Date是方法setTime(Date date),但方法名称不明确,并且文档不清楚调用此方法实际上会做什么。显然我不能只做calendar.set( date.getYear(), date.getMonth(), ..)等,因为这些方法已Date被弃用。

So how can I convert a given Date object to Calendar?

那么如何将给定的 Date 对象转换为 Calendar?

采纳答案by Jeff Storey

Calendar cal = Calendar.getInstance();
cal.setTime(date);

You can get the calendar in different locales as well if you want.

如果需要,您也可以在不同的语言环境中获取日历。

You could also do

你也可以这样做

cal.setTimeInMillis(date.getTime());