Java中將字符串轉(zhuǎn)換為時(shí)間戳的方法有多種。以下是其中幾種常用的方法:
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();
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();
String dateString = "2021-01-01 12:00:00";
Timestamp timestamp = Timestamp.valueOf(dateString);
long timestampInMilliseconds = timestamp.getTime();
這些方法中,都需要先將字符串按照特定的日期格式解析為Date對象或LocalDateTime對象,然后再將其轉(zhuǎn)換為時(shí)間戳。