kotlin 获取yyyymmddhh24miss格式的日期
时间: 2023-04-04 10:03:03 浏览: 211
可以使用 SimpleDateFormat 类来获取 yyyymmddhh24miss 格式的日期,示例代码如下:
```kotlin
import java.text.SimpleDateFormat
import java.util.*
fun main() {
val dateFormat = SimpleDateFormat("yyyyMMddHHmmss")
val currentDate = Date()
val formattedDate = dateFormat.format(currentDate)
println(formattedDate)
}
```
输出结果为当前时间的 yyyymmddhh24miss 格式的日期。
相关问题
kotlin中获取yyyy-MM-dd HH:mm:ss格式的当前时间
在Kotlin中,你可以使用`java.time`包中的`LocalDateTime`类来获取当前时间,并使用`DateTimeFormatter`类来格式化时间。
首先,确保你的项目已经导入了`java.time`包。在Kotlin中,你可以使用以下代码获取当前时间并格式化为"yyyy-MM-dd HH:mm:ss"格式:
```kotlin
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
fun getCurrentDateTime(): String {
val currentDateTime = LocalDateTime.now()
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
return currentDateTime.format(formatter)
}
fun main() {
val currentDateTime = getCurrentDateTime()
println(currentDateTime)
}
```
这段代码定义了一个名为`getCurrentDateTime`的函数,它使用`LocalDateTime.now()`获取当前时间,然后使用`DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")`创建一个格式化器,最后使用`currentDateTime.format(formatter)`将当前时间格式化为指定的格式。
在`main`函数中,你可以调用`getCurrentDateTime`函数来获取当前时间并打印输出。
运行这段代码,你将会得到当前时间的"yyyy-MM-dd HH:mm:ss"格式输出。
kotlin中使用Date()获取yyyy-MM-dd HH:mm:ss格式的当前时间
在Kotlin中,可以使用`java.util.Date`类和`java.text.SimpleDateFormat`类来获取当前时间并将其格式化为"yyyy-MM-dd HH:mm:ss"格式。
```kotlin
import java.util.Date
import java.text.SimpleDateFormat
fun getCurrentDateTime(): String {
val currentDate = Date()
val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
return dateFormat.format(currentDate)
}
fun main() {
val currentDateTime = getCurrentDateTime()
println(currentDateTime)
}
```
这段代码定义了一个名为`getCurrentDateTime`的函数,它使用`Date()`创建一个表示当前时间的Date对象。然后,使用`SimpleDateFormat("yyyy-MM-dd HH:mm:ss")`创建一个格式化器,最后使用`dateFormat.format(currentDate)`将当前时间格式化为指定的格式。
在`main`函数中,你可以调用`getCurrentDateTime`函数来获取当前时间并打印输出。
运行这段代码,你将会得到当前时间的"yyyy-MM-dd HH:mm:ss"格式输出。请注意,`java.util.Date`类在Java 8及更高版本中已经过时,推荐使用`java.time`包中的新日期时间API。