Java将字符串日期转换为秒

时间:2022-05-17 02:03:01

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 +'。

3 个解决方案

#1


3  

Joda-Time

Don't reinvent the wheel. The Joda-Time library can parse those values for you. No need for regex.

不要重新发明*。 Joda-Time库可以为您解析这些值。不需要正则表达式。

ISO 8601

Those values are close to being in standard ISO 8601 format. Specifically the Durations format, PnYnMnDTnHnMnS. The P marks the beginning, the T separates the date portion from the time position. If you have time-only values, then simply prepend the PT to get PT33m03s. Lastly convert to uppercase to get PT33M03S.

这些值接近于标准ISO 8601格式。特别是持续时间格式,PnYnMnDTnHnMnS。 P标记开头,T将日期部分与时间位置分开。如果您只有时间值,则只需在PT前面加上PT33m03s。最后转换为大写以获得PT33M03S。

Joda-Time both parses and generates such strings by default. Once your input is in standard format, you can pass it directly to Joda-Time. Skip the regex.

Joda-Time默认解析并生成这样的字符串。输入为标准格式后,您可以直接将其传递给Joda-Time。跳过正则表达式。

Alternatively, you can specify a PeriodFormatter to fit your exact input strings. Then you can parse the original input strings without converting to standard format.

或者,您可以指定PeriodFormatter以适合您的确切输入字符串。然后,您可以解析原始输入字符串,而无需转换为标准格式。

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

Next, use the Period class to automatically parse that value into a Period object. 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.)

接下来,使用Period类自动将该值解析为Period对象。期间表示一个时间跨度,以月,日,小时等为单位。与宇宙历史时间轴上的点无关。 (如果时间轴上有特定点,请使用Interval类。)

Duration Class

Next, call toStandardDuration to get a Duration object. A Duration in Joda-Time represents a span of time as just the passage of time. Merely a number of milliseconds, not a specific number of months or hours or such chunks.

接下来,调用StandardDuration以获取Duration对象。 Joda-Time中的持续时间表示一段时间,就像时间的流逝一样。仅仅是几毫秒,而不是特定的月或小时数或这样的块。

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

#2


1  

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();

#3


0  

You might want to use String's substring method to extract the number you want and parse it to an integer. For example just to get seconds you can do:

您可能希望使用String的substring方法提取所需的数字并将其解析为整数。例如,你可以做几秒钟:

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;

#1


3  

Joda-Time

Don't reinvent the wheel. The Joda-Time library can parse those values for you. No need for regex.

不要重新发明*。 Joda-Time库可以为您解析这些值。不需要正则表达式。

ISO 8601

Those values are close to being in standard ISO 8601 format. Specifically the Durations format, PnYnMnDTnHnMnS. The P marks the beginning, the T separates the date portion from the time position. If you have time-only values, then simply prepend the PT to get PT33m03s. Lastly convert to uppercase to get PT33M03S.

这些值接近于标准ISO 8601格式。特别是持续时间格式,PnYnMnDTnHnMnS。 P标记开头,T将日期部分与时间位置分开。如果您只有时间值,则只需在PT前面加上PT33m03s。最后转换为大写以获得PT33M03S。

Joda-Time both parses and generates such strings by default. Once your input is in standard format, you can pass it directly to Joda-Time. Skip the regex.

Joda-Time默认解析并生成这样的字符串。输入为标准格式后,您可以直接将其传递给Joda-Time。跳过正则表达式。

Alternatively, you can specify a PeriodFormatter to fit your exact input strings. Then you can parse the original input strings without converting to standard format.

或者,您可以指定PeriodFormatter以适合您的确切输入字符串。然后,您可以解析原始输入字符串,而无需转换为标准格式。

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

Next, use the Period class to automatically parse that value into a Period object. 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.)

接下来,使用Period类自动将该值解析为Period对象。期间表示一个时间跨度,以月,日,小时等为单位。与宇宙历史时间轴上的点无关。 (如果时间轴上有特定点,请使用Interval类。)

Duration Class

Next, call toStandardDuration to get a Duration object. A Duration in Joda-Time represents a span of time as just the passage of time. Merely a number of milliseconds, not a specific number of months or hours or such chunks.

接下来,调用StandardDuration以获取Duration对象。 Joda-Time中的持续时间表示一段时间,就像时间的流逝一样。仅仅是几毫秒,而不是特定的月或小时数或这样的块。

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

#2


1  

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();

#3


0  

You might want to use String's substring method to extract the number you want and parse it to an integer. For example just to get seconds you can do:

您可能希望使用String的substring方法提取所需的数字并将其解析为整数。例如,你可以做几秒钟:

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;