获取当前时间,格式为yyyy-MM-dd HH:mm:ss,并转换为Date类型 输出格式为yyyy-MM-dd HH:mm:ss
时间: 2024-05-10 16:20:27 浏览: 13
Java代码实现:
```
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = sdf.format(new Date());
System.out.println(currentTime);
try {
Date date = sdf.parse(currentTime);
System.out.println(sdf.format(date));
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
输出结果:
```
2022-07-15 13:28:20
2022-07-15 13:28:20
```
相关问题
获取当前时间,格式为yyyy-MM-dd HH:mm:ss,并转换为Date类型 java
可以使用以下代码获取当前时间,并将其转换为Date类型:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class CurrentTime {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = sdf.format(new Date());
System.out.println("Current Time: " + currentTime);
try {
Date date = sdf.parse(currentTime);
System.out.println("Date object: " + date);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
输出:
```
Current Time: 2022-05-14 13:10:23
Date object: Sat May 14 13:10:23 CST 2022
```
js获取当前时间格式为(YYYY-MM-DD 24hh:mm:ss
要获取当前时间并格式化为"YYYY-MM-DD 24hh:mm:ss"的格式,可以使用JavaScript的Date对象和相关方法来实现。下面是一种实现方式:
```javascript
// 创建一个Date对象
var currentDate = new Date();
// 获取年、月、日、小时、分钟和秒
var year = currentDate.getFullYear();
var month = ('0' + (currentDate.getMonth() + 1)).slice(-2);
var day = ('0' + currentDate.getDate()).slice(-2);
var hours = ('0' + currentDate.getHours()).slice(-2);
var minutes = ('0' + currentDate.getMinutes()).slice(-2);
var seconds = ('0' + currentDate.getSeconds()).slice(-2);
// 格式化为指定的字符串格式
var formattedDate = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
console.log(formattedDate); // 输出格式化后的时间字符串
```
这段代码首先创建了一个Date对象,然后使用Date对象的方法获取当前的年、月、日、小时、分钟和秒。接着使用字符串拼接的方式将这些值组合成指定的格式,并将结果打印出来。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)