Java获取yyyy-MM-dd HH:mm:ss格式的当前时间
时间: 2024-06-17 19:06:17 浏览: 22
在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 方法将其格式化成字符串,最后输出即可。
相关问题
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"表示月份。
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。