java 日期类格式输出
时间: 2023-08-31 19:06:23 浏览: 102
Java 日期类可以使用 SimpleDateFormat 类来进行格式化输出。以下是一个示例代码,将当前日期格式化为 "yyyy-MM-dd HH:mm:ss" 的字符串:
```
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateExample {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = formatter.format(date);
System.out.println(formattedDate);
}
}
```
输出结果为当前日期的格式化字符串,例如 "2022-06-01 14:30:00"。你可以根据需要修改 SimpleDateFormat 中的格式化字符串来输出不同格式的日期。
相关问题
java常用类之日期类格式化模式之输出时间
输出时间的日期类格式化模式可以使用以下代码实现:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatExample {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(date);
System.out.println("当前时间:" + formattedDate);
}
}
```
其中,`SimpleDateFormat` 是日期格式化类,可以通过传入不同的格式化模式来输出不同格式的时间。常用的格式化模式包括:
- `yyyy`:年份,如 2021
- `MM`:月份,如 01、02、03 等
- `dd`:日期,如 01、02、03 等
- `HH`:小时,24 小时制,如 00、01、02 等
- `mm`:分钟,如 00、01、02 等
- `ss`:秒钟,如 00、01、02 等
以上格式化模式可以组合使用,例如 `yyyy-MM-dd HH:mm:ss` 就是输出年月日时分秒的格式。
java中date格式输出
在Java中,可以使用SimpleDateFormat类来将Date对象格式化为指定的日期/时间字符串。以下是一个简单的示例,将Date对象格式化为yyyy-MM-dd HH:mm:ss格式的字符串:
```
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateDemo {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = dateFormat.format(date);
System.out.println(dateString);
}
}
```
输出结果类似于:2021-11-23 16:23:45