我想从 Java 日期中获取年、月、日等,以与 Java 中的公历日期进行比较.这可能吗? [英] I want to get Year, Month, Day, etc from Java Date to compare with Gregorian Calendar date in Java. Is this possible?

查看:21
本文介绍了我想从 Java 日期中获取年、月、日等,以与 Java 中的公历日期进行比较.这可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Java 中有一个 Date 对象存储为 Java 的 Date 类型.

I have a Date object in Java stored as Java's Date type.

我还有一个公历创建日期.公历日期没有参数,因此是今天日期(和时间?)的一个实例.

I also have a Gregorian Calendar created date. The gregorian calendar date has no parameters and therefore is an instance of today's date (and time?).

使用 java 日期,我希望能够从 java 日期类型中获取年、月、日、小时、分钟和秒,并比较 gregoriancalendar 日期.

With the java date, I want to be able to get the year, month, day, hour, minute, and seconds from the java date type and compare the the gregoriancalendar date.

我看到目前 Java 日期存储为 long 并且唯一可用的方法似乎只是将 long 写入格式化的日期字符串.有没有办法访问年、月、日等?

I saw that at the moment the Java date is stored as a long and the only methods available seem to just write the long as a formatted date string. Is there a way to access Year, month, day, etc?

我看到Date 类的getYear()getMonth() 等方法已被弃用.我想知道使用带有 GregorianCalendar 日期的 Java 日期实例的最佳实践是什么.

I saw that the getYear(), getMonth(), etc. methods for Date class have been deprecated. I was wondering what's the best practice to use the Java Date instance I have with the GregorianCalendar date.

我的最终目标是进行日期计算,以便我可以检查 Java 日期是否在今天日期和时间的几小时、几分钟等范围内.

My end goal is to do a date calculation so that I can check that the Java date is within so many hours, minutes etc of today's date and time.

我还是 Java 的新手,对此有点困惑.

I'm still a newbie to Java and am getting a bit puzzled by this.

推荐答案

使用类似:

Date date; // your date
// Choose time zone in which you want to interpret your Date
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Paris"));
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
// etc.

注意,月份从 0 开始,而不是 1.

Beware, months start at 0, not 1.

编辑:从 Java 8 开始,最好使用 java.time.LocalDate 而不是 java.util.Calendar.请参阅此答案了解如何操作.

Edit: Since Java 8 it's better to use java.time.LocalDate rather than java.util.Calendar. See this answer for how to do it.

这篇关于我想从 Java 日期中获取年、月、日等,以与 Java 中的公历日期进行比较.这可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆