簡體   English   中英

Java JodaTime:“ 123”應為(長)123。如何在沒有“ ms”作為結尾的情況下做到這一點:例如“ 10ms”?

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

如何從Java-JodaTime格式化PeriodFormatter以處理類似以下的字符串:
“ 10s” =(長)10000; <-我解決了。
“ 10ms” =(長)10。
“ 10” =長10。<-僅這是我的問題!

我可以通過此鏈接使用Joda Time處理前兩個命令:
解析時間字符串,例如“ 1h 30min”

但是我的問題是:如何將“ 10”轉換為毫厘克。 沒有空的追加?

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

我在文檔或Google中找不到任何內容。 因此,感謝您的幫助。

作為一種解決方法,我使用Joda-Code上方的正則表達式來捕獲內部僅包含數字的字符串:

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

如果輸入不包含文字,則只需將其從構建器模式中刪除即可。 因此,使用以下簡單代碼即可解決僅將數字解析為毫秒的問題:

   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

這里是沒有regexp的解決方案:

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

老實說,這有點"1s10ms10" ,而且還會解析一個像"1s10ms10"這樣的字符串,這很尷尬,但是這是您不應該遇到的邊緣情況,更重要的是,它將實現您想要的。 將正確評估以下字符串: "1s10ms""1s""10ms""10"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM