指定日期转时间戳 代码示例 java
时间: 2023-09-14 12:11:22 浏览: 54
你好,以下是将指定日期转换为时间戳的Java代码示例:
```
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateToTimestamp {
public static void main(String[] args) throws Exception {
String dateString = "2022-06-10 12:00:00";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = dateFormat.parse(dateString);
long timestamp = date.getTime() / 1000; // 时间戳单位为秒
System.out.println(timestamp);
}
}
```
以上代码将字符串类型的时间 `"2022-06-10 12:00:00"` 转换为 `Date` 类型,然后通过 `getTime()` 方法获取时间戳,最终结果为 `1654905600`,表示在指定时间点之前的所有时间都可以用这个时间戳来表示。
希望对你有所帮助!如果你还有其他问题,请随时提出。
相关问题
java 时间戳转日期
Java中时间戳转日期可以通过使用`java.util.Date`类和`java.text.SimpleDateFormat`类来实现。下面是一个示例代码:
```java
import java.util.Date;
import java.text.SimpleDateFormat;
public class TimestampToDate {
public static void main(String[] args) {
long timestamp = 1622877366000L; // 假设时间戳为 1622877366000
// 创建一个Date对象并传入时间戳
Date date = new Date(timestamp);
// 创建SimpleDateFormat对象来指定日期格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 使用SimpleDateFormat的format()方法将日期转换为字符串
String formattedDate = sdf.format(date);
System.out.println("转换后的日期为: " + formattedDate);
}
}
```
以上代码将时间戳`1622877366000`转换为格式为`yyyy-MM-dd HH:mm:ss`的日期字符串输出。你可以根据需要修改日期格式。
Java 毫秒时间戳转换日期格式
可以使用 Java 的 SimpleDateFormat 类来进行毫秒时间戳转换日期格式,示例代码如下:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
long timestamp = 1620473154000L; // 毫秒时间戳
String pattern = "yyyy-MM-dd HH:mm:ss"; // 日期格式
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
String dateStr = sdf.format(new Date(timestamp));
System.out.println(dateStr);
}
}
```
输出结果为:
```
2021-05-08 20:19:14
```
其中,`timestamp` 是毫秒时间戳,`pattern` 是要转换成的日期格式,`SimpleDateFormat` 是日期格式化类,`format` 方法将 `Date` 对象转换成指定格式的字符串。