java 时间戳 string转long
时间: 2023-07-20 07:10:29 浏览: 59
在Java中,可以使用`SimpleDateFormat`类将字符串类型的时间转换为时间戳。具体代码如下:
```java
String timeString = "2021-01-01 00:00:00"; // 时间字符串
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 定义时间格式
Date date = sdf.parse(timeString); // 将时间字符串解析为Date对象
long timestamp = date.getTime(); // 获取时间戳,单位为毫秒
```
需要注意的是,`SimpleDateFormat`类的构造函数需要传入时间格式,时间格式中的字符代表不同的时间单位,例如`yyyy`表示年份,`MM`表示月份,`dd`表示日期,`HH`表示小时,`mm`表示分钟,`ss`表示秒等。详细的时间格式可以参考Java官方文档。
另外,`getTime()`方法返回的时间戳单位为毫秒,如果需要以秒为单位,可以将返回值除以1000。
相关问题
java Long时间戳转String
时间,你可以使用SimpleDateFormat类中的format()方法将Long类型的时间戳转换为String类型的时间格式,具体代码如下:
long timestamp = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = sdf.format(new Date(timestamp));
System.out.println(date);
输出结果为:2021-11-02 19:30:45
笑话:为什么Java开发者喜欢喝茶?因为Java是一种高度“对象”化的语言,所以他们喜欢用“类”泡茶。
时间戳long 转String
将时间戳long转换为String的方法有多种。根据你提供的引用内容,可以采用以下方法之一:
1. 使用SimpleDateFormat类进行格式化:
```
// 假设时间戳为timestamp
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = sdf.format(new Date(timestamp));
```
2. 使用DateTimeFormatter类进行格式化(适用于Java 8及以上版本):
```
// 假设时间戳为timestamp
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String dateString = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault()).format(dtf);
```
请注意,使用哪种方法取决于你的具体需求以及所用的Java版本。
相关推荐
![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_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)