java String时间戳转换为TimeStamp
时间: 2024-04-29 14:20:59 浏览: 9
可以使用Java中的SimpleDateFormat类将字符串时间戳转换为TimeStamp对象。
以下是一个示例代码:
```java
String timestampString = "1622802523000"; // 时间戳字符串
long timestamp = Long.parseLong(timestampString);
Timestamp ts = new Timestamp(timestamp);
// 输出转换后的TimeStamp对象
System.out.println(ts);
```
输出结果:
```
2021-06-04 14:55:23.0
```
注意,时间戳字符串的格式必须是"yyyy-MM-dd HH:mm:ss.SSS",否则转换会失败。如果需要使用其他格式的时间戳字符串,可以先将其转换为对应的Date对象,再使用Date对象构建TimeStamp对象。
相关问题
java long时间戳转换为LocalDateTime
在Java中,可以使用`java.time`包中的类来进行`long`时间戳到`LocalDateTime`的转换。下面是一个示例代码:
```java
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
public class TimestampConverter {
public static LocalDateTime convertTimestamp(long timestamp) {
Instant instant = Instant.ofEpochMilli(timestamp);
return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
}
public static void main(String[] args) {
long timestamp = 1621234567890L;
LocalDateTime dateTime = convertTimestamp(timestamp);
System.out.println(dateTime);
}
}
```
在上面的代码中,`convertTimestamp`方法接受一个`long`类型的时间戳作为参数,并使用`Instant.ofEpochMilli`方法将时间戳转换为`Instant`对象。然后,使用`LocalDateTime.ofInstant`方法将`Instant`对象转换为本地日期时间对象`LocalDateTime`。最后,可以通过打印输出来查看转换后的结果。
Java中将时间戳转换为字符串
在Java中,可以使用`SimpleDateFormat`类将时间戳转换为字符串。下面是示例代码:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimestampToString {
public static void main(String[] args) {
long timestamp = 1620047224000L; // 时间戳
Date date = new Date(timestamp);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = sdf.format(date);
System.out.println("时间戳 " + timestamp + " 转换为字符串:" + strDate);
}
}
```
输出结果为:
```
时间戳 1620047224000 转换为字符串:2021-05-03 14:00:24
```
在上述代码中,`SimpleDateFormat`类的构造函数中指定了时间格式,即`"yyyy-MM-dd HH:mm:ss"`,可以根据需要更改时间格式。