java 时间转字符串
时间: 2023-07-20 22:09:28 浏览: 41
在 Java 中,可以使用 SimpleDateFormat 类将时间转换为字符串。以下是一个示例代码:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimeToStringExample {
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: " + formattedDate);
}
}
```
在上面的代码中,我们创建一个 Date 对象表示当前时间,并使用 SimpleDateFormat 类将其格式化为字符串。格式化字符串 "yyyy-MM-dd HH:mm:ss" 表示年份(4 位数)、月份、日期、小时、分钟和秒,中间用连字符和冒号分隔。最后,我们将格式化后的字符串打印到控制台上。
相关问题
java时间转字符串
可以使用Java中的SimpleDateFormat类将时间转换为字符串。示例代码如下:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimeToString {
public static void main(String[] args) {
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strTime = sdf.format(now);
System.out.println(strTime);
}
}
```
其中,now为当前时间,sdf指定了时间格式,strTime为转换后的字符串。
java 时间转字符串2021-09-01T12:00:00Z
如果你要将 "2021-09-01T12:00:00Z" 这种格式的时间转换为字符串,可以使用 SimpleDateFormat 类。以下是一个示例代码:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimeToStringExample {
public static void main(String[] args) {
String timeString = "2021-09-01T12:00:00Z";
SimpleDateFormat inputFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
SimpleDateFormat outputFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = inputFormatter.parse(timeString);
String formattedDate = outputFormatter.format(date);
System.out.println("Formatted date: " + formattedDate);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在上面的代码中,我们首先定义了输入和输出格式化器。输入格式化器用于将字符串解析为 Date 对象,输出格式化器用于将 Date 对象格式化为字符串。然后我们尝试将输入字符串解析为 Date 对象,并使用输出格式化器将其格式化为字符串。最后,我们将格式化后的字符串打印到控制台上。注意,在解析日期字符串时,需要将 "T" 和 "Z" 用单引号括起来,表示它们是字面量而不是格式化字符。