现在我在数据库中的日期为Long:
val time = target?.date ?: 0L
我将其转换为日期:
val date = Date(time)
然后将其用作字符串以显示我的日期:
val format = SimpleDateFormat("d MMMM, yyyy")
format.format(date)
一切正常
但是现在我只想使用DateTimeFormatter
做同样的事情
有可能吗?
答案 0 :(得分:0)
尝试这样做:
val shortFormat : DateTimeFormatter =
DateTimeFormat.forPattern("MM/dd/yy").withZone(PST)
val formatted : String = shortFormat.print(time)
答案 1 :(得分:0)
在继续阅读之前,您应该先查看DateTimeFormatter
class的文档。无论如何,您都可以使用LocalDate
和DateTimeFormatter
类。
看一下LocalDate
class文档,我发现有一种方法可以允许通过LocalDate#ofEpochDay
方法指定一个long。
无论如何,DateTimeFormatter
类文档中有一个代码示例,我将在此处逐字复制,但适用于使用LocalDate#ofEpochDay
方法:
val date = LocalDate.ofEpochDay(target?.date ?: 0L)
val formatter = DateTimeFormatter.ofPattern("d MMMM, yyyy")
val format = date.format(formatter)
此外,我已经缩短了解决您的问题所需的代码量。
希望这会有所帮助! (P.S.到目前为止,我尚未测试上面的代码示例。)
答案 2 :(得分:0)
您应该将Date
对象转换为LocalDate
,然后直接进行转换。这是使用Kotlin Playground
fun formatMillisUsingDateTimeFormatter(millis: Long): String {
val date = Date(millis).toInstant().atZone(ZoneId.systemDefault()).toLocalDate()
val formatter = DateTimeFormatter.ofPattern("d MMMM yyyy", Locale.getDefault())
return date.format(formatter)
}
LocalDate
对象具有#format,该对象直接获取DateTimeFormatter
并将其自身转换为字符串。现在,要将Date
对象转换为LocalDate
对象,需要进行多次转换,我建议您反对,但是您需要先将其转换为Instant,然后再转换为ZonedDateTime最后到LocalDate。
答案 3 :(得分:0)
如@edric所述,我们可以使用LocalDate来格式化DateTimeFormatter,
要将长时间(以毫秒为单位)转换为<xsl:output cdata-section-elements="..."/>
,我们可以使用多种方式。
LocalDate
第一种方法(参考:java.time.LocalDate#now(java.time.Clock)或org.threeten.bp.LocalDate#now(java.time.Clock))
val dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy MM dd")
我们可以使用LocalDate.ofEpochDay(Math.floorDiv(time, 24 * 60 * 60 * 1000)).format(dateTimeFormatter)
2。
Calendar
3。
var time = target?.date ?: 0L
var calendar = Calendar.getInstance()
calendar.timeInMillis = time
LocalDate.of(calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH) + 1,
calendar.get(Calendar.DAY_OF_MONTH)
).format(dateTimeFormatter)