如何将整数从 datePicker 格式化为日期字符串

How to format Ints from datePicker to date-string

我可以从日期选择器中获取日期值:

override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
    Log.i("onDateSet", year.toString())
    Log.i("onDateSet", month.toString())
    Log.i("onDateSet", dayOfMonth.toString())
}

如何将此整数格式化为日期字符串,例如:2020-05-05

而且我看到月份总是返回一个月前,如果今天是第5个月,它返回第4个月。 这是一个错误还是我只是它的工作原理,我需要将我从日期选择器获得的每个月加 1?

AndroidSDK's Date class

所述

A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so forth; thus 11 is December.

An hour is represented by an integer from 0 to 23. Thus, the hour from midnight to 1 a.m. is hour 0, and the hour from noon to 1 p.m. is hour 12.

A minute is represented by an integer from 0 to 59 in the usual manner.

A second is represented by an integer from 0 to 61; the values 60 and 61 occur only for leap seconds.

日期和年份按常规方式表示,而上述内容则按其各自的规则表示。

因此,如果是 5 月,它将 return 4,如果是 6 月,它将 return 5,依此类推。

注意:虽然这种行为可能看起来很奇怪,但它与 java.util.Calendar class 一致(尽管它与 joda.time.DateTime 不一致)。

文档说 month int: the selected month (0-11 for compatibility with Calendar#MONTH),所以是的,这是所需的行为,要将其格式化为人类可读,我想你必须添加 1。

对于格式化字符串,您可能应该手动连接您拥有的数据

val date = "$year-${month+1}-$day"

(对我来说是最快的方法,但你可以选择更漂亮的方法)

或者你可以这样做:

val date = LocalDate(year, monthOfYear + 1, dayOfMonth).toString("yyyy-MM-dd")