java实现时间戳转为年月日时分秒(附完整源码)
时间: 2023-11-09 09:05:33 浏览: 110
可以使用Java中的SimpleDateFormat类来实现时间戳转为年月日时分秒的功能。以下是完整的源码:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimestampToDate {
public static void main(String[] args) {
long timestamp = 1582068992000L; // 时间戳,精确到毫秒
Date date = new Date(timestamp); // 时间戳转为Date对象
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 设置日期格式
String formatTime = sdf.format(date); // 格式化时间
System.out.println(formatTime); // 输出结果:2020-02-19 14:16:32
}
}
```
通过以上代码,我们可以将一个时间戳转换为年月日时分秒的格式,并输出结果。其中,SimpleDateFormat类中的日期格式可以根据实际需求进行修改。
相关问题
java年月日T时分Z 转为时间戳或年月日时分秒格式
Java中使用以下代码可以将字符串类型的时间转换为时间戳:
```java
String timeStr = "2022-10-01T12:30Z";
Instant instant = Instant.parse(timeStr);
long timeStampMillis = instant.toEpochMilli();
```
如果要将时间戳转换为年月日时分秒格式,可以使用以下代码:
```java
long timeStampMillis = System.currentTimeMillis();
Instant instant = Instant.ofEpochMilli(timeStampMillis);
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String timeStr = formatter.format(localDateTime);
```
其中,DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") 可以根据需要自定义时间格式。
年月日T时分Z 转为时间戳或年月日时分秒格式
年月日T时分Z表示的是ISO 8601格式的时间字符串,可以使用Python内置的datetime模块来进行转换。
将年月日T时分Z转换为时间戳:
```python
from datetime import datetime
time_str = '2021-10-01T12:34:56Z'
timestamp = datetime.strptime(time_str, '%Y-%m-%dT%H:%M:%SZ').timestamp()
print(timestamp) # 输出1633076096.0
```
将年月日T时分Z转换为年月日时分秒格式:
```python
from datetime import datetime
time_str = '2021-10-01T12:34:56Z'
dt = datetime.strptime(time_str, '%Y-%m-%dT%H:%M:%SZ')
time_format = dt.strftime('%Y-%m-%d %H:%M:%S')
print(time_format) # 输出2021-10-01 12:34:56
```
需要注意的是,年月日时分秒格式的输出结果可能会受到系统时区的影响。