用Java 将时间戳转为 yyyy-mm-ddthh:mm:ssz 格式的字符串
时间: 2024-05-11 13:16:15 浏览: 24
可以使用Java的SimpleDateFormat类将时间戳转换为yyyy-MM-dd'T'HH:mm:ss'Z'格式的字符串,如下所示:
```
long timestamp = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String formattedDate = sdf.format(timestamp);
System.out.println(formattedDate);
```
这将输出类似于“2021-08-16T03:25:42Z”的字符串,其中“Z”表示UTC时间。您可以根据需要调整格式字符串和时区。
相关问题
java毫秒时间戳转换yyyy-MM-dd HH:mm:ss格式
你可以使用Java中的 `SimpleDateFormat` 类将毫秒时间戳转换为 `yyyy-MM-dd HH:mm:ss` 格式的日期字符串。以下是一个示例代码:
```java
long timestamp = 1625065654000L; // 毫秒时间戳
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = sdf.format(new Date(timestamp));
System.out.println(dateStr); // 输出格式化后的日期字符串
```
在上面的代码中,我们首先定义了一个毫秒时间戳 `timestamp`。然后,我们创建了一个 `SimpleDateFormat` 对象 `sdf`,并将其格式指定为 `yyyy-MM-dd HH:mm:ss`。接下来,我们使用 `new Date(timestamp)` 将毫秒时间戳转换为 `Date` 对象,并使用 `sdf.format()` 方法将其格式化为字符串。最后,我们使用 `System.out.println()` 打印出格式化后的日期字符串。
需要注意的是,`SimpleDateFormat` 类是线程不安全的,如果在多线程环境中使用,需要进行同步处理。
JS时间戳转为yyyy-mm-dd hh:mm:ss
可以使用以下代码将 JavaScript 时间戳转换为 yyyy-mm-dd hh:mm:ss 格式的日期和时间:
```javascript
function timestampToDatetime(timestamp) {
const date = new Date(timestamp);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDate()).padStart(2, "0");
const hours = String(date.getHours()).padStart(2, "0");
const minutes = String(date.getMinutes()).padStart(2, "0");
const seconds = String(date.getSeconds()).padStart(2, "0");
const formattedDatetime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
return formattedDatetime;
}
const timestamp = 1623342000000; // 示例时间戳
const formattedDatetime = timestampToDatetime(timestamp);
console.log(formattedDatetime);
```
请将 `timestamp` 替换为你要转换的实际时间戳。这段代码将输出格式为 `yyyy-mm-dd hh:mm:ss` 的日期和时间字符串。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)