如何在 Java 中创建日历对象

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

How to create a calendar object in Java

java

提问by flyingfromchina

I need to turn a Date object into a calendar in Java, and try to access its field value for HOUR_OF_DAY. Does anybody know how to do it?

我需要在 Java 中将 Date 对象转换为日历,并尝试访问其 HOUR_OF_DAY 的字段值。有人知道怎么做吗?

采纳答案by Jo?o Silva

Use the setTimemethod:

使用setTime方法:

Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);

回答by Jim Garrison

Calendar c = new GregorianCalendar();
c.setTime(date);

回答by Tamas Mezei

Something like this should work:

这样的事情应该工作:

Calendar cal = Calendar.getInstance();
cal.setTime(date);
System.out.println(cal.get(Calendar.HOUR_OF_DAY));

回答by Brian Agnew

Can I suggest using the Joda libraryif you're doing anything more than the most basic date/time work ?

如果您所做的不仅仅是最基本的日期/时间工作,我可以建议使用Joda 库吗?

DateTime dt = new DateTime();
int hour = dt.getHourOfDay();

I realise it's not quite what you're after, but the Joda date/time library offers the benefits of a muchnicer and intuitive API, and avoids the non-intuitive gotchas of non-thread-safe date/time formatters It's well worth checking out.

我意识到这不是很你以后,但乔达日期/时间库提供一个好处漂亮和直观的API,并且避免了非线程安全的日期/时间格式化的非直观的陷阱这是很值得的检查出去。