分析前检查日期格式 [英] Check date format before parsing
本文介绍了分析前检查日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用字段持续时间
解析几个文档。但是在不同的文件中,这是不同的格式,例如:
持续时间:00:43
持续时间:113.046
持续时间:21.55 s
希望将它们全部解析为格式Duration:113.046
,我怎么能在任何解析之前检查它是什么格式?
这段代码之前的一些条件,因为这是不正确的所有这些:
持续时间长;
DateFormat sdf = new SimpleDateFormat(hh:mm:ss);
尝试{
日期durationD = sdf.parse(totalDuration);
日期zeroSec = sdf.parse(00:00:00);
duration = durationD.getTime() - zeroSec.getTime();
} catch(Exception e){
duration = Long.parseLong(totalDuration);
$ b $ p
$ p
.htmlrel =nofollow noreferrer> regex 然后格式。这里有一个启发的例子:
Map< Pattern,DateFormat> dateFormatPatterns = new HashMap< Pattern,DateFormat>();
dateFormatPatterns.put(Pattern.compile(\\\\\ {1,2}:\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
dateFormatPatterns.put(Pattern.compile(\\\\\\\\\\\\\\\\\\\\\\\\'
dateFormatPatterns.put(Pattern.compile(\\\\\\\\\\\\\\\\\\' );
String [] strings = {00:43,113.046,21.55 s};
DateFormat finalFormat = new SimpleDateFormat(HH:mm:ss); (字符串string:字符串){
for(Pattern pattern:dateFormatPatterns.keySet()){
if(pattern.matcher(string).matches()){
$ b $
Date date = dateFormatPatterns.get(pattern).parse(string);
String formattedTime = finalFormat.format(date);
System.out.println(formattedTime);
break;
$ p >
00:43:00
00:01:53
00:00:21
I am parsing several documments with the field Duration
. But in the differents files, it is in differnt formats, ex:
"Duration": "00:43"
"Duration": "113.046"
"Duration": "21.55 s"
I want to parse all of them to the format "Duration": "113.046"
, how could I check before any parsing in wich format it is??
Some conditions before this piece of code, because this is not right for all of them:
Long duration;
DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
try {
Date durationD = sdf.parse(totalDuration);
Date zeroSec = sdf.parse("00:00:00");
duration = durationD.getTime() - zeroSec.getTime();
} catch (Exception e) {
duration = Long.parseLong(totalDuration);
}
Thanks in advance
解决方案 You could match the pattern with help of regex and then format accordingly. Here's a kickoff example:
Map<Pattern, DateFormat> dateFormatPatterns = new HashMap<Pattern, DateFormat>();
dateFormatPatterns.put(Pattern.compile("\\d{1,2}:\\d{2}"), new SimpleDateFormat("H:m"));
dateFormatPatterns.put(Pattern.compile("\\d{1,3}\\.\\d{3}"), new SimpleDateFormat("s.S"));
dateFormatPatterns.put(Pattern.compile("\\d{1,2}\\.\\d{2} s"), new SimpleDateFormat("s.S 's'"));
String[] strings = { "00:43", "113.046", "21.55 s" };
DateFormat finalFormat = new SimpleDateFormat("HH:mm:ss");
for (String string : strings) {
for (Pattern pattern : dateFormatPatterns.keySet()) {
if (pattern.matcher(string).matches()) {
Date date = dateFormatPatterns.get(pattern).parse(string);
String formattedTime = finalFormat.format(date);
System.out.println(formattedTime);
break;
}
}
}
This yields here
00:43:00
00:01:53
00:00:21
这篇关于分析前检查日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文