如何从 edittext 中获取给定年份的第三个星期三?

How to get the third wednesday of given year from edittext?

我想制作一个应用程序,用户可以在该应用程序中将数字(年份)放入编辑文本中,当您单击该按钮时,用户会在该年 4 月的第三个星期三进入文本视图。例如,他们输入 2020,结果得到日期 15.04.2020。那是 2020 年 4 月的第三个星期三。我有一个编辑文本、一个按钮和一个文本视图。谢谢你的帮助。

问题已解决谢谢:

LocalDateTemporalAdjuster

使用TemporalAdjuster implementation TemporalAdjusters.dayOfWeekInMonth.

使用 Integer class 将您的年份数字文本输入解析为 int

获取指定年份的第一天作为 LocalDate 对象。

Year y = Year.of( 2021 ) ;
LocalDate startOfYear = y.atDay( 1 ) ;  // First day of the year.

移至 4 月。使用 immutable objects,所以我们得到一个新的新对象而不是改变 ("mutate") 原始对象。

LocalDate ld = startOfYear.with( Month.APRIL ) ;  // Move to the first of April, our desired month.

获取本月第 3 个星期三的时间调整器实施。

int ordinal = 3 ;  // Third such day of the month.
DayOfWeek dow = DayOfWeek.WEDNESDAY ;
TemporalAdjuster ta = TemporalAdjusters.dayOfWeekInMonth( ordinal , dow ) ;

应用调整器获得另一个 LocalDate 对象,即我们想要的结果,该月的第三个星期三。

LocalDate thirdWednesdayOfApril = ld.with( ta ) ;  // Move to the 3rd Wednesday of April of the specified year.

要生成特定格式的文本以呈现给用户,请使用 DateTimeFormatter.ofLocalizedDate。搜索以了解更多信息,因为这已在 Stack Overflow 上多次解决。


关于java.time

java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

要了解更多信息,请参阅 Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310

Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

您可以直接与数据库交换 java.time 对象。使用 JDBC driver compliant with JDBC 4.2 或更高版本。不需要字符串,不需要 java.sql.* classes。 Hibernate 5 和 JPA 2.2 支持 java.time

从哪里获得java.time classes?