从日历中获取 18 年前的日期 [英] Getting 18 years before date from calender

查看:32
本文介绍了从日历中获取 18 年前的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获得 18 年后的完整日期(dd/mm/yyyy).我用代码作为日历计算 = Calendar.getInstance();calc.add(Calendar.YEAR, -18);它在一年之前而不是月份或日期之前检索 18 年.即使在任何一个月的第一天这样的极端情况下,我也需要比当前日期早 18 年的一天.示例 1-06-2015 是当前日期应为 31-05-1997.请注意,我需要 java6 中的代码

I need to get complete date(dd/mm/yyyy) which is 18 years from now. i used code as Calendar calc = Calendar.getInstance(); calc.add(Calendar.YEAR, -18); which retrives 18 years before year not month or date. I need one day 18 years before current date even in corner cases like 1st of any month also. Example 1-06-2015 is current date should get 31-05-1997.To be noted i need code in java6

推荐答案

在 Java 中,日期值只是某个固定时间点的毫秒数,相关类不携带自己的格式可以更改,这就是日期/时间格式化程序的用途

In Java, a date value is just the number of milliseconds from some fixed point in time, the related classes don't carry a format of their own which you can change, this is what date/time formatters are for

从您的示例中,您基本上忽略了这样一个事实,即更改任何 Calendar 的字段都会影响所有其他字段,例如...

From your example, you're basically ignoring the fact that changing any of the Calendar's fields, will effect all the others, for example...

Calendar cal = Calendar.getInstance();
cal.set(2015, Calendar.JUNE, 01); // Comment this out for today...
cal.add(Calendar.YEAR, -18);
cal.add(Calendar.DATE, -1);
Date date = cal.getTime();
System.out.println(new SimpleDateFormat("dd/MM/yyyy").format(date));

哪些输出

31/05/1997

不过,我建议使用 Java 8 的新 Time API 或 Joda-Time

I would, however, recommend using either Java 8's new Time API or Joda-Time

LocalDate ld = LocalDate.now();
ld = ld.minusYears(18).minusDays(1);
System.out.println(DateTimeFormatter.ofPattern("dd/MM/yyyy").format(ld));

哪些输出

26/06/1997

边缘情况...

LocalDate ld = LocalDate.of(2015, Month.JUNE, 1);
ld = ld.minusYears(18).minusDays(1);
System.out.println(DateTimeFormatter.ofPattern("dd/MM/yyyy").format(ld));

哪些输出

31/05/1997

JodaTime

LocalDate ld = new LocalDate();
ld = ld.minusYears(18).minusDays(1);
System.out.println(DateTimeFormat.forPattern("dd/MM/yyyy").print(ld));

哪些输出

26/06/1997

边缘情况...

LocalDate ld = new LocalDate(2015, DateTimeConstants.JUNE, 1);
ld = ld.minusYears(18).minusDays(1);
System.out.println(DateTimeFormat.forPattern("dd/MM/yyyy").print(ld));

哪些输出

31/05/1997

这篇关于从日历中获取 18 年前的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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