我怎么才能得到年份列表对话框

时间:2016-08-26 22:02:09

标签: java android date

我想创建一个仅显示年份的列表选择器。

但我希望明年这一年会自动增加。

我尝试使用DatePicker执行此操作,但它不会仅显示年份选择器。

我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

使用java.time

使用java.time类,它是麻烦的旧遗留日期时间类的现代替代品。

确定年份意味着确定日期。确定日期需要时区。对于任何给定的时刻,日期在全球范围内因地区而异。例如,法国巴黎午夜过后几分钟是新的一天,而在魁北克蒙特利尔仍然是“昨天”。

如果未指定,则应用JVM的当前默认时区。默认情况会有所不同,即使在运行时也是如此。因此,最好明确指定所需/预期的时区。

                    A pid_t indicating the process that currently owns exclusive access to the
                    AudioDevice or a value of -1 indicating that the device is currently
                    available to all processes. If the AudioDevice is in a non-mixable mode,
                    the HAL will automatically take hog mode on behalf of the first process to
                    start an IOProc.
                    Note that when setting this property, the value passed in is ignored. If
                    another process owns exclusive access, that remains unchanged. If the
                    current process owns exclusive access, it is released and made available to
                    all processes again. If no process has exclusive access (meaning the current
                    value is -1), this process gains ownership of exclusive access.  On return,
                    the pid_t pointed to by inPropertyData will contain the new value of the
                    property.

如果您只想要一年,这个时区问题显然只适用于年底/年初。但是你可以把它编程为一年365或366天的一般工作。

ZoneId z = ZoneId.of( "America/Montreal" );

LocalDate类表示没有时间且没有时区的仅限日期的值。

LocalDate

最后审问这一年。

LocalDate ld = LocalDate.now( z );

计算明年和去年。

int year = ld.getYear();

现在使用这些值来显示数字选择器。

关于java.time

java.time框架内置于Java 8及更高版本中。这些类取代了旧的麻烦日期时间类,例如int nextYear = ( year + 1 ); int lastYear = ( year - 1 ); java.util.Date和& .Calendar

现在位于Joda-Timemaintenance mode项目建议迁移到java.time。

要了解详情,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。

大部分java.time功能都被反向移植到Java 6& ThreeTen-Backport中的7,并进一步适应Android中的ThreeTenABP(见How to use…)。

ThreeTen-Extra项目使用其他类扩展java.time。该项目是未来可能添加到java.time的试验场。

答案 1 :(得分:0)

使用默认的TimePicker是不可能的。但是,你可以实施MH。" hacky" solution

或者,你可以简单地使用NumberPicker并列出你想要的年份。