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

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

问题描述



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



随着java日期,我想能够得到一年日期,时间,分钟和秒数,并比较gregoriancalendar日期。



我看到,Java日期存储在一个长而唯一的方法似乎只是写一个格式化的日期字符串长。有没有办法访问年,月,日等?



我看到 getYear() getMonth()等。 Date 类的方法已被弃用。我想知道使用Java日期实例的最佳做法是使用 GregorianCalendar 日期。



我的结束目标是做一个日期计算,以便我可以检查Java日期是否在今天日期和时间的许多小时,分钟等内。



我还是一个新手对于Java而言,这让我感到困惑。

解决方案

使用类似于

 日期日期; //你的日期
日历cal = Calendar.getInstance();
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
//等

小心,月份从0开始,不是1。 >

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?).

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.

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?

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.

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.

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

解决方案

Use something like:

    Date date; // your date
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    int year = cal.get(Calendar.YEAR);
    int month = cal.get(Calendar.MONTH);
    int day = cal.get(Calendar.DAY_OF_MONTH);
    // etc.

Beware, months start at 0, not 1.

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

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