简体   繁体   English

Java将字符串日期转换为秒

[英]Java converting string date to seconds

I have some inputs: 我有一些输入:

1h50m22s
2h40m10s
33m03s

And I have to convert to seconds in java. 而且我必须在Java中转换为秒。

Already extract numbers with regex '\\d+|\\D+'. 已经使用正则表达式'\\ d + | \\ D +'提取数字。

Joda-Time 乔达时代

Don't reinvent the wheel. 不要重新发明轮子。 The Joda-Time library can parse those values for you. Joda-Time库可以为您解析这些值。 No need for regex. 无需正则表达式。

ISO 8601 ISO 8601

Those values are close to being in standard ISO 8601 format. 这些值接近于标准ISO 8601格式。 Specifically the Durations format, PnYnMnDTnHnMnS . 具体来说, 持续时间格式PnYnMnDTnHnMnS The P marks the beginning, the T separates the date portion from the time position. P标记开始, T标记日期部分与时间位置。 If you have time-only values, then simply prepend the PT to get PT33m03s . 如果您只有时间值,则只需在PT添加PT33m03s Lastly convert to uppercase to get PT33M03S . 最后转换为大写字母以获得PT33M03S

Joda-Time both parses and generates such strings by default. 默认情况下,Joda-Time会解析并生成此类字符串。 Once your input is in standard format, you can pass it directly to Joda-Time. 输入为标准格式后,您可以将其直接传递给Joda-Time。 Skip the regex. 跳过正则表达式。

Alternatively, you can specify a PeriodFormatter to fit your exact input strings. 或者,您可以指定一个PeriodFormatter以适合您的确切输入字符串。 Then you can parse the original input strings without converting to standard format. 然后,您可以解析原始输入字符串,而无需转换为标准格式。

If you have any control or influence over the source of your input strings, I strongly suggest altering that source to utilize the ISO 8601 format. 如果您对输入字符串的来源有任何控制或影响,强烈建议您更改该来源以利用ISO 8601格式。

Period Class Period

Next, use the Period class to automatically parse that value into a Period object. 接下来,使用Period类将该值自动解析为Period对象。 A Period represents a span of time as a number of months, days, hours, and such. 周期表示时间跨度,以月,天,小时等数表示。 Not tied to points on the timeline of the history of the Universe. 依赖于宇宙历史时间表上的时间点。 (If you have specific points on a timeline, use the Interval class.) (如果您在时间轴上有特定的点,请使用Interval类。)

Duration Class Duration

Next, call toStandardDuration to get a Duration object. 接下来,调用toStandardDuration以获取Duration对象。 A Duration in Joda-Time represents a span of time as just the passage of time. Joda-Time中的Duration表示时间跨度,只是时间的流逝。 Merely a number of milliseconds, not a specific number of months or hours or such chunks. 仅是毫秒数,而不是特定的月数或小时数或此类块数。

Lastly, on that Duration object call getStandardSeconds to get your answer. 最后,在Duration对象上,调用getStandardSeconds以获取答案。

Much easier than dealing with regex. 比处理正则表达式容易得多。 And more reliable as Joda-Time is already built, debugged, well-worn, and able to handle the various permutations of possible input strings. 而且,由于Joda-Time已被构建,调试,磨损且能够处理可能的输入字符串的各种排列,因此更加可靠。

Example Code 范例程式码

Using Joda-Time 2.5. 使用Joda-Time 2.5。

Succinct version (not recommended). 简洁版本(不推荐)。

String input = ( "PT" + "33m03s" ).toUpperCase();
long durationInSeconds = Period.parse( input ).toStandardDuration().getStandardSeconds();

Detailed version. 详细版本。

// Convert input string to standard ISO 8601 format.
// Alternatively, you could use a formatter to parse your original string rather than convert.
String inputRaw = "33m03s";
String inputStandard = "PT" + inputRaw; // Assuming this is a time-only without date portion, prepend 'PT' to make standard ISO 8601 format.
inputStandard = inputStandard.toUpperCase();

// Parse string as Period object.
Period period = Period.parse( inputStandard );

// Convert from Period to Duration to extract total seconds.
Duration duration = period.toStandardDuration();
long durationInSeconds = duration.getStandardSeconds();  // Returns getMillis() / 1000. The result is an integer division, so 2999 millis returns 2 seconds.

Dump to console. 转储到控制台。

System.out.println( "inputRaw : " + inputRaw );
System.out.println( "inputStandard : " + inputStandard );
System.out.println( "period : " + period );  // Notice how the leading zero on the 'seconds' number is gone. We have a Period *object*, not messing with strings.
System.out.println( "duration : " + duration );
System.out.println( "durationInSeconds : " + durationInSeconds );

When run. 运行时。

inputRaw : 33m03s
inputStandard : PT33M03S
period : PT33M3S
duration : PT1983S
durationInSeconds : 1983

You can easily do it using Joda-Time . 您可以使用Joda-Time轻松地做到这一点。

Using Pattern class first in order to extract fields: 首先使用Pattern类以提取字段:

Pattern pattern = Pattern.compile("(?:(\\d+)h)?(?:(\\d+)m)?(?:(\\d+)s)?");
Matcher matcher = pattern.matcher("1h50m22s");
matcher.matches();
String hours = matcher.group(1);
String minutes = matcher.group(2);
String seconds = matcher.group(3);

Period period = new Period();
if(hours != null){
    period = period.withHours(Integer.parseInt(hours));
}
if(minutes != null){
    period = period.withMinutes(Integer.parseInt(minutes));
}
if(seconds != null){
    period = period.withSeconds(Integer.parseInt(seconds));
}
int totalSeconds = period.toStandardSeconds().getSeconds();

Using PeriodFormatterBuilder class (less flexible for parsing patterns): 使用PeriodFormatterBuilder类(对于分析模式不太灵活):

String dateText = "1h50m22s";
PeriodFormatterBuilder formatterBuilder = new PeriodFormatterBuilder();

if(dateText.contains("h")){
    formatterBuilder.appendHours().appendLiteral("h");
}
if(dateText.contains("m")){
    formatterBuilder.appendMinutes().appendLiteral("m");
}
if(dateText.contains("s")){
    formatterBuilder.appendSeconds().appendLiteral("s");
}

Period period = formatterBuilder.toFormatter().parsePeriod(dateText);
int totalSeconds = period.toStandardSeconds().getSeconds();

You might want to use String's substring method to extract the number you want and parse it to an integer. 您可能想使用String的substring方法提取所需的数字并将其解析为整数。 For example just to get seconds you can do: 例如,只需几秒钟,您可以执行以下操作:

String time = "32h45m93s";
String seconds = time.substring(time.indexOf('m') + 1, time.indexOf('s'));
int seconds = Integer.parseInt(seconds);

I didn't run it, but this is the general idea. 我没有运行它,但这是一般的想法。 Do the same with hours and minutes and then 用小时和分钟做同样的事情,然后

int totalSeconds = hours * 3600 + minutes * 60 + seconds;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM