简体   繁体   中英

Java JodaTime: “123” should be (long) 123. How can I do that without having “ms” for example at the end: “10ms”?

How do I format the PeriodFormatter from Java-JodaTime to handle Strings like:
"10s" = (long) 10000; <-- I solved that.
"10ms" = (long) 10.
"10" = long 10. <-- Only here is my problem!

I can handle the first two commands with Joda Time with this link:
Parsing time strings like "1h 30min"

But my problem: How can I convert the "10" to millisec. without an empty appending?

    PeriodFormatter formatter = new PeriodFormatterBuilder()
       .appendSeconds().appendSuffix("s")
       .appendMillis().appendSuffix("ms")
       .append###########().appendSuffix("")  // <--here is my problem. Keep it empty won't work: InvalidFormatException
       .toFormatter();
    Period p = formatter.parsePeriod("10s"); // <-- this works
    p = formatter.parsePeriod("10");   // <-- Here is my problem. It should be 10 millisec.
    System.out.println("Time in millisec.: "+p.getMillis());

I could not find anything in the doc or at Google. So thanks for your help.

As a workaround I am using a regular expression above of the Joda-Code to catch strings with only digits inside:

    if (time.matches("[0-9]+")) {
        return Long.parseLong(time);
    }     
    PeriodFormatter formatter = new PeriodFormatterBuilder() 
        .appendWeeks().appendSuffix("w")                     
        .appendDays().appendSuffix("d")
        .appendHours().appendSuffix("h")
        .appendMinutes().appendSuffix("m")
        .appendSeconds().appendSuffix("s")            
        .appendMillis().appendSuffix("ms")            
        .toFormatter();     
    return p.toStandardDuration().getMillis();      

If the input does not contain a literal then simply leave it out from your builder-pattern. So parsing only a number to milliseconds can be solved with following simple code:

   PeriodFormatter pf = new PeriodFormatterBuilder()
       .appendMillis()
       .toFormatter();
   Period p = pf.parsePeriod("10");
   System.out.println("Time in millisec.: " + p);
   // Time in millisec.: PT0.010S
   System.out.println("Time in millisec.: " + p.getMillis());
   // Time in millisec.: 10

Here a solution without regexp:

PeriodFormatter f = new PeriodFormatterBuilder()
            .appendSeconds().appendSuffix("s")
            .appendMillis().appendSuffix("ms")
            .appendMillis()
            .toFormatter();

To be honest, this a bit of an hack and will also parse a string like "1s10ms10" which is awkward, BUT this an edge case that you should not encounter and, more importantly, will achieve what you want. The following strings will be correctly evaluated: "1s10ms" , "1s" , "10ms" , "10"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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