是否有一个Java库将描述时间度量的字符串(例如“1d 1m 1s”)转换为毫秒?(Is there a java library that converts strings describing m

编程入门 行业动态 更新时间:2024-10-26 04:20:37
是否有一个Java库将描述时间度量的字符串(例如“1d 1m 1s”)转换为毫秒?(Is there a java library that converts strings describing measures of time (e.g. “1d 1m 1s”) to milliseconds?)

在JIRA中设置问题估算值时,您可以输入一个字符串,如"1d 2h 30m" ,JIRA会将此(我假设)转换为相应的毫秒数。

有没有可用的Java库来做到这一点?

我使用的是一个Spring托管bean,它接受一个属性,指明目录应该被清除的频率,并且我希望允许配置采用人类可读的字符串,而不是明确的毫秒数。

或者,如果我没有想到更好的方法,我很乐意听到它。

When setting issue estimates in JIRA, you can enter a string like "1d 2h 30m" and JIRA will translate this (I'm assuming) into a corresponding number of milliseconds.

Is there an available Java library that does this?

I'm using a Spring managed bean that takes a property indicating how often a directory ought to be purged, and I'd like to allow the configuration to take a human-readable string rather than an explicit number of milliseconds.

Alternatively, if there's a better approach I'm not thinking of, I'd love to hear it.

最满意答案

解析器不太复杂:

public static long parse(String input) { long result = 0; String number = ""; for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (Character.isDigit(c)) { number += c; } else if (Character.isLetter(c) && !number.isEmpty()) { result += convert(Integer.parseInt(number), c); number = ""; } } return result; } private static long convert(int value, char unit) { switch(unit) { case 'd' : return value * 1000*60*60*24; case 'h' : return value * 1000*60*60; case 'm' : return value * 1000*60; case 's' : return value * 1000; } return 0; }

该代码具有相当的容错能力,它只是忽略了它无法解码的任何东西(并且忽略了任何空白区域,所以它接受“1d 1s”,“1s 1d”,“1d20m300s”等等)。

The parser is not too complex:

public static long parse(String input) { long result = 0; String number = ""; for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (Character.isDigit(c)) { number += c; } else if (Character.isLetter(c) && !number.isEmpty()) { result += convert(Integer.parseInt(number), c); number = ""; } } return result; } private static long convert(int value, char unit) { switch(unit) { case 'd' : return value * 1000*60*60*24; case 'h' : return value * 1000*60*60; case 'm' : return value * 1000*60; case 's' : return value * 1000; } return 0; }

The code is pretty fault tolerant, it just ignores almost anything it can't decode (and it ignores any whitspace, so it accepts "1d 1s", "1s 1d", "1d20m300s" and so on).

更多推荐

JIRA,I'm,字符串,Java,电脑培训,计算机培训,IT培训"/> <meta name="descri

本文发布于:2023-07-22 20:48:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1223306.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:度量   字符串   转换为   有一个   时间

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!