您的位置:

Java时间转换为时间戳

引言

在Java开发中,经常需要将不同格式的时间转换成时间戳。时间戳是指从Unix纪元1970-01-01 00:00:00开始的秒数,它是一个长整型。Java提供了多种方式来将时间转换为时间戳,比如使用SimpleDateFormat类、Calendar类以及JDK8新引入的DateTimeFormatter类等。

SimpleDateFormat类

使用SimpleDateFormat将String格式的时间转换为时间戳

public static long StringToTimestamp(String dateStr) throws ParseException {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = dateFormat.parse(dateStr);
    return date.getTime();
}

在上述代码中,我们使用SimpleDateFormat类初始化一个日期格式,然后将日期字符串转换为Date对象,最后通过Date对象获取时间戳。

使用SimpleDateFormat将java.util.Date类型的时间转换为时间戳

public static long dateToTimestamp(Date date) {
    return date.getTime();
}

这段代码中,我们直接将java.util.Date类型的时间转换为时间戳。

Calendar类

使用Calendar将java.util.Date类型的时间转换为时间戳

public static long dateToTimestamp2(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    return calendar.getTimeInMillis();
}

Calendar类也可以用来将java.util.Date类型的时间转换为时间戳。我们首先初始化一个Calendar对象,并设置其时间为要转换的日期,最后调用getTimeInMillis()方法获取时间戳。

DateTimeFormatter类

使用DateTimeFormatter将String类型的时间转换为时间戳

public static long StringToTimestamp2(String dateStr) {
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    LocalDateTime localDateTime = LocalDateTime.parse(dateStr, dateTimeFormatter);
    return localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
}

在JDK8中,新增了DateTimeFormatter类来提供更好的时间格式化和解析功能。我们可以使用它将String类型的时间转换为DateTime对象,再转换为时间戳。

总结

以上介绍了Java中将时间转换为时间戳的几种常用方法,分别使用了SimpleDateFormat、Calendar和DateTimeFormatter类。其中,SimpleDateFormat是应用广泛的一种方式,但是不支持线程安全,所以在多线程的情况下需要注意。另外,在JDK8中新增的DateTimeFormatter类提供了更好的日期格式化和解析功能,也可以进行时间戳的转换。