Java中将字符串转换为时间戳的方法有多种。以下是其中几种常用的方法:
使用SimpleDateFormat类:String dateString = "2021-01-01 12:00:00";SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date date = sdf.parse(dateString);long timestamp = date.getTime();使用DateTimeFormatter类(Java 8及以上版本):String dateString = "2021-01-01 12:00:00";DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");LocalDateTime localDateTime = LocalDateTime.parse(dateString, dtf);long timestamp = localDateTime.toInstant(ZoneOffset.UTC).toEpochMilli();使用java.sql.Timestamp类:String dateString = "2021-01-01 12:00:00";Timestamp timestamp = Timestamp.valueOf(dateString);long timestampInMilliseconds = timestamp.getTime();这些方法中,都需要先将字符串按照特定的日期格式解析为Date对象或LocalDateTime对象,然后再将其转换为时间戳。

