[英]Android calendar get previous to previous month of previous year
I am facing issue with android calendar, I want to get previous to previous month, when i am trying it with current year this will achieve my goal, but when i am trying with previous year it fails.我遇到了 android 日历的问题,我想在上个月之前,当我在今年尝试它时,这将实现我的目标,但是当我尝试上一年时它失败了。 in my case today is 29/apr/2020 and i want feb/2019 return from calendar.
就我而言,今天是 2020 年 4 月 29 日,我希望 2019 年 2 月从日历返回。 please help me with this.
请帮我解决一下这个。
my code is following我的代码如下
Date dt = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
int month = cal.get(Calendar.MONTH) - 2; // beware of month indexing from zero
int year = cal.get(Calendar.YEAR)-1;
int day = cal.get(Calendar.DAY_OF_MONTH);
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month);
String formatMonth = new SimpleDateFormat("MMM").format(cal.getTime());
String formatYear = new SimpleDateFormat("yy").format(cal.getTime());```
Allow me to suggest that you use java.time, the modern Java date and time API, for your date work.请允许我建议您使用 java.time,即现代 Java 日期和时间 API 进行日期工作。
YearMonth currentMonth = YearMonth.of(2020, Month.APRIL);
YearMonth backThen = currentMonth.minusYears(1).minusMonths(2);
String formatMonth = backThen.format(DateTimeFormatter.ofPattern("MMM"));
String formatYear = backThen.format(DateTimeFormatter.ofPattern("yy"));
System.out.printf("Month %s; year %s%n", formatMonth, formatYear);
Output on my computer is (locale dependent):我的计算机上的 Output 是(取决于区域设置):
Month feb.;
二月; year 19
19 年
For the sake of a reproducible example I hardcoded the year and month.为了一个可重现的例子,我硬编码了年份和月份。 To start from the current month in some time zone use something like this:
要从某个时区的当前月份开始,请使用以下内容:
YearMonth currentMonth = YearMonth.now(ZoneId.of("Europe/Minsk"));
It's the poor and confusing design of the Calendar
and GregorianCalendar
classes.这是
Calendar
和GregorianCalendar
类的糟糕和令人困惑的设计。
You said you ran your code on 29/apr/2020.您说您在 2020 年 4 月 29 日运行了代码。 This causes your
Calendar
to be set back to 29th February 2019. This date does not exist;这会导致您的
Calendar
被设置回 2019 年 2 月 29 日。这个日期不存在; there were only 28 days in February last year.去年2月只有28天。 Instead
Calendar
picks the day after February 28, that is, March 1. Causing you to get an incorrect month.相反,
Calendar
选择 2 月 28 日之后的一天,即 3 月 1 日。导致您获得错误的月份。
java.time works nicely on both older and newer Android devices. java.time 适用于较旧和较新的 Android 设备。 It just requires at least Java 6 .
它只需要至少Java 6 。
org.threeten.bp
with subpackages.org.threeten.bp
导入日期和时间类。java.time
was first described. java.time
。java.time
to Java 6 and 7 (ThreeTen for JSR-310). java.time
到 Java 6 和 7 的 backport(ThreeTen for JSR-310)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.