java格式化输出时间
时间: 2023-10-14 20:08:58 浏览: 48
在Java中,可以使用SimpleDateFormat类来格式化时间。以下是一个示例:
```
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
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("Formatted date and time: " + formattedDate);
}
}
```
在上面的示例中,我们使用了SimpleDateFormat类将当前日期和时间格式化为"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 formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
System.out.println(formatter.format(date));
}
}
```
输出结果为当前时间的格式化字符串,例如:2021-07-22 15:30:00。
java格式化输出%
Java 格式化输出主要使用 % 操作符和格式化字符串来实现。下面是一个简单的例子:
```java
String name = "小明";
int age = 20;
System.out.printf("我的名字是 %s,我今年 %d 岁。\n", name, age);
```
上面的代码中,%s 和 %d 是格式化字符串中的占位符,它们分别表示字符串和整数类型。在 printf 方法中,占位符 %s 和 %d 将会被传递进来的变量替换掉。
以下是常见的格式化字符串占位符:
| 占位符 | 类型 |
| --- | --- |
| %s | 字符串 |
| %d | 整数 |
| %f | 浮点数 |
| %c | 字符 |
| %b | 布尔值 |
| %x | 十六进制整数 |
在格式化字符串中,可以使用一些控制字符来控制输出的格式,例如:
| 控制字符 | 功能 |
| --- | --- |
| %n | 换行 |
| %% | 输出百分号 |
| %t | 时间和日期 |
| %- | 左对齐 |
| %0 | 补零 |
以下是一个例子:
```java
String name = "小明";
double score = 90.5;
System.out.printf("%-10s %.2f%n", name, score);
```
上面的代码中,%10s 表示左对齐宽度为 10 的字符串类型,%.2f 表示保留两位小数的浮点数类型,%n 表示换行。
相关推荐
![](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)