java中获取当前时间并转为yyyy-mm-dd hh:mm:ss
时间: 2024-12-10 18:34:02 浏览: 1130
在Java中,你可以使用`java.time`包下的`LocalDateTime`类来获取当前日期和时间,并通过`format()`方法将其转换为"yyyy-MM-dd HH:mm:ss"这种格式。以下是一个示例:
```java
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class CurrentTimeExample {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now(); // 获取当前日期和时间
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 定义日期时间格式
String formattedDate = now.format(formatter); // 格式化当前时间为字符串
System.out.println("当前时间: " + formattedDate);
}
}
```
当你运行这个程序,它会打印出类似这样的结果:"当前时间: 2023-04-07 15:30:00"。
相关问题
yyyy-MM-dd'T'HH:mm:ss转yyyy-MM-dd HH:mm:ss
要将yyyy-MM-dd'T'HH:mm:ss格式的日期时间转换为yyyy-MM-dd HH:mm:ss格式,可以按照以下步骤进行转换:
1. 首先,将输入的字符串解析为日期时间对象。可以使用Java中的SimpleDateFormat类来实现。示例代码如下:
```java
String inputDateTime = "yyyy-MM-dd'T'HH:mm:ss";
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date = inputFormat.parse(inputDateTime);
```
2. 接下来,将日期时间对象格式化为目标格式的字符串。同样使用SimpleDateFormat类,示例代码如下:
```java
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String outputDateTime = outputFormat.format(date);
```
最后,outputDateTime就是转换后的yyyy-MM-dd HH:mm:ss格式的日期时间字符串。
java将yyyy-MM-dd HH:mm:ss 转为yyyy-MM-dd
可以使用Java中的SimpleDateFormat类来进行日期格式化。具体的代码如下:
```java
String dateString = "2022-11-11 11:11:11";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = dateFormat.parse(dateString);
dateFormat.applyPattern("yyyy-MM-dd");
String output = dateFormat.format(date);
System.out.println(output);
```
代码中首先定义了一个日期字符串dateString和一个SimpleDateFormat对象dateFormat,dateFormat的格式为"yyyy-MM-dd HH:mm:ss"。
然后使用dateFormat的parse方法将日期字符串解析为Date对象。
接着使用applyPattern方法将dateFormat的格式修改为"yyyy-MM-dd"。
最后使用dateFormat的format方法将Date对象格式化为字符串并输出。
阅读全文
相关推荐
















