1、通过SimpleDateFormat
package se.wederbrand.milliseconds;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String inputString = "00:01:30.500";
Date date = sdf.parse("1970-01-01 " + inputString);
System.out.println("in milliseconds: " + date.getTime());
}
}
注意:
- 所有日期均在内部以UTC表示
- getTime() 返回自1970-01-01 00:00:00 UTC以来的毫秒数
2、通过正则表达式
private static Pattern pattern = Pattern.compile("(\\d{2}):(\\d{2}):(\\d{2}).(\\d{3})");
public static long dateParseRegExp(String period) {
Matcher matcher = pattern.matcher(period);
if (matcher.matches()) {
return Long.parseLong(matcher.group(1)) * 3600000L
+ Long.parseLong(matcher.group(2)) * 60000
+ Long.parseLong(matcher.group(3)) * 1000
+ Long.parseLong(matcher.group(4));
} else {
throw new IllegalArgumentException("Invalid format " + period);
}
}