Java获取yyyy-MM-dd HH:mm:ss格式的当前时间
时间: 2024-06-17 22:06:17 浏览: 258
在Java中获取当前时间并格式化成 yyyy-MM-dd HH:mm:ss 的字符串可以使用如下代码:
```
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String formattedDate = formatter.format(date);
System.out.println(formattedDate);
}
}
```
其中,SimpleDateFormat 类可以将 Date 类型的日期格式化成字符串,而 "yyyy-MM-dd HH:mm:ss" 则是指定的日期格式。这里先创建了一个 SimpleDateFormat 对象 formatter,指定日期格式为 "yyyy-MM-dd HH:mm:ss",然后获取当前时间的 Date 对象并调用 formatter 对象的 format 方法将其格式化成字符串,最后输出即可。
相关问题
根据yyyy-MM-dd HH:mm:ss 获取 yyyy-MM-dd 和 HH:mm:ss
你可以通过Java中的日期处理API来获取给定日期和时间的部分信息。如果你有一个字符串`dateStr`按照"yyyy-MM-dd HH:mm:ss"的格式存储,可以使用`SimpleDateFormat`来解析它,并分别提取出年、月、日和小时、分钟、秒。
首先,你需要创建一个`SimpleDateFormat`对象来匹配输入的日期格式:
```java
String inputFormat = "yyyy-MM-dd HH:mm:ss";
String outputFormat1 = "yyyy-MM-dd"; // 提取日期部分
String outputFormat2 = "HH:mm:ss"; // 提取时间部分
SimpleDateFormat inputFormatter = new SimpleDateFormat(inputFormat);
Date date = null;
try {
date = inputFormatter.parse(dateStr);
} catch (ParseException e) {
// 处理日期格式错误
}
if (date != null) {
SimpleDateFormat dateFormat = new SimpleDateFormat(outputFormat1);
String yearMonthDay = dateFormat.format(date);
SimpleDateFormat timeFormat = new SimpleDateFormat(outputFormat2);
String hourMinSec = timeFormat.format(date);
}
```
这样,`yearMonthDay`变量将包含"yyyy-MM-dd"格式的日期,而`hourMinSec`变量将包含"HH:mm:ss"格式的时间。
java获取yyyy-MM-dd HH:mm:ss格式的当前时间
可以使用如下代码获取当前时间并格式化为 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 sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = sdf.format(new Date());
System.out.println(currentTime);
}
}
```
输出结果为当前时间的字符串表示,格式为:yyyy-MM-dd HH:mm:ss。
阅读全文
相关推荐
















