亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Golang 解析 time.Duration

Golang 解析 time.Duration

Go
繁星coding 2021-09-13 10:36:33
我想解析time.Duration. 持續時間是"PT15M"(字符串/字節),并希望將其轉換為有效的time.Duration.如果這是一time.Time件事,我會使用:t, err := time.Parse(time.RFC3339Nano, "2013-06-05T14:10:43.678Z")但這不存在(ParseDuration只需要一個參數):d, err := time.ParseDuration(time.RFC3339Nano, "PT15M")如何解析此ISO 8601 持續時間?
查看完整描述

2 回答

?
慕村9548890

TA貢獻1884條經驗 獲得超4個贊

它并不完全是“開箱即用”,而是正則表達式可以完成這項工作:


package main


import "fmt"

import "regexp"

import "strconv"

import "time"


func main() {

    fmt.Println(ParseDuration("PT15M"))

    fmt.Println(ParseDuration("P12Y4MT15M"))

}


func ParseDuration(str string) time.Duration {

    durationRegex := regexp.MustCompile(`P(?P<years>\d+Y)?(?P<months>\d+M)?(?P<days>\d+D)?T?(?P<hours>\d+H)?(?P<minutes>\d+M)?(?P<seconds>\d+S)?`)

    matches := durationRegex.FindStringSubmatch(str)


    years := ParseInt64(matches[1])

    months := ParseInt64(matches[2])

    days := ParseInt64(matches[3])

    hours := ParseInt64(matches[4])

    minutes := ParseInt64(matches[5])

    seconds := ParseInt64(matches[6])


    hour := int64(time.Hour)

    minute := int64(time.Minute)

    second := int64(time.Second)

    return time.Duration(years*24*365*hour + months*30*24*hour + days*24*hour + hours*hour + minutes*minute + seconds*second)

}


func ParseInt64(value string) int64 {

    if len(value) == 0 {

        return 0

    }

    parsed, err := strconv.Atoi(value[:len(value)-1])

    if err != nil {

        return 0

    }

    return int64(parsed)

}



查看完整回答
反對 回復 2021-09-13
?
交互式愛情

TA貢獻1712條經驗 獲得超3個贊

這是處理分數時間單位的代碼,如PT3.001S.


var durationRegex = regexp.MustCompile(`P([\d\.]+Y)?([\d\.]+M)?([\d\.]+D)?T?([\d\.]+H)?([\d\.]+M)?([\d\.]+?S)?`)


// ParseDuration converts a ISO8601 duration into a time.Duration

func ParseDuration(str string) time.Duration {

   matches := durationRegex.FindStringSubmatch(str)


   years := parseDurationPart(matches[1], time.Hour*24*365)

   months := parseDurationPart(matches[2], time.Hour*24*30)

   days := parseDurationPart(matches[3], time.Hour*24)

   hours := parseDurationPart(matches[4], time.Hour)

   minutes := parseDurationPart(matches[5], time.Second*60)

   seconds := parseDurationPart(matches[6], time.Second)


   return time.Duration(years + months + days + hours + minutes + seconds)

}


func parseDurationPart(value string, unit time.Duration) time.Duration {

   if len(value) != 0 {

       if parsed, err := strconv.ParseFloat(value[:len(value)-1], 64); err == nil {

           return time.Duration(float64(unit) * parsed)

       }

   }

   return 0

}


查看完整回答
反對 回復 2021-09-13
  • 2 回答
  • 0 關注
  • 472 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號