Aha*_*med 20 java time timestamp simpledateformat
我有一个00:01:30.500相当于90500毫秒的字符串.我尝试过使用SimpleDateFormat包含当前日期的毫秒数.我只需要字符串表示毫秒.我是否必须编写自定义方法,它将分割并计算毫秒数?或者还有其他办法吗?谢谢.
我试过如下:
String startAfter = "00:01:30.555";
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss.SSS");
Date date = dateFormat.parse(startAfter);
System.out.println(date.getTime());
Run Code Online (Sandbox Code Playgroud)
And*_*and 38
你可以SimpleDateFormat用来做.你只需要知道两件事.
.getTime() 返回自1970-01-01 00:00:00 UTC以来的毫秒数.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());
}
}
Run Code Online (Sandbox Code Playgroud)
如果您想自己解析格式,可以使用正则表达式轻松完成
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);
}
}
Run Code Online (Sandbox Code Playgroud)
但是,这种解析非常宽松,可以接受99:99:99.999,只是让值溢出.这可能是一个缺点或特征.
| 归档时间: |
|
| 查看次数: |
119331 次 |
| 最近记录: |