java 中 怎么获取"yyyy-MM-dd HH:mm:ss"格式化后的时间值
时间: 2024-03-09 20:44:42 浏览: 27
可以使用Java的SimpleDateFormat类来将日期格式化为指定的字符串格式。下面是一个示例代码,可以获取当前时间并将其格式化为"yyyy-MM-dd HH:mm:ss"格式的字符串:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
// 创建SimpleDateFormat对象,指定日期格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 获取当前时间
Date now = new Date();
// 将当前时间格式化为指定格式的字符串
String formattedDate = sdf.format(now);
// 输出格式化后的时间字符串
System.out.println(formattedDate);
}
}
```
输出结果类似于:2021-07-07 14:30:00
相关问题
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"格式输出。
java获取yyyy-mm-dd hh:mi:ss
要在Java中获取当前日期和时间的格式为"yyyy-mm-dd hh:mi:ss",可以使用Java的SimpleDateFormat类。下面是一个示例代码:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
// 创建SimpleDateFormat对象,指定日期时间格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 获取当前日期时间
Date date = new Date();
// 使用SimpleDateFormat格式化日期时间
String formattedDateTime = sdf.format(date);
// 打印格式化后的日期时间
System.out.println(formattedDateTime);
}
}
```
运行以上代码,将会输出当前的日期和时间,格式为"yyyy-mm-dd hh:mi:ss"。请注意,"mm"表示分钟,"MM"表示月份。