How to Convert ISO 8601 Duration to TimeSpan in VB.Net?

前端 未结 3 1882
死守一世寂寞
死守一世寂寞 2020-12-30 04:38

Is there a standard library method that converts a string that has duration in the standard ISO 8601 Duration (also used in XSD for its duration type) format in

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-30 04:39

    One minor word of caution - XmlConvert.ToTimeSpan() is a little funny when working with months and years. The TimeSpan class does not have month or year members, probably because their length varies. However, ToTimeSpan() will happily accept a duration string with month or year values in it and guess at a duration, instead of throwing an exception. Observe:

    PS C:\Users\troll> [Reflection.Assembly]::LoadWithPartialName("System.Xml")
    
    GAC    Version        Location
    ---    -------        --------
    True   v2.0.50727     C:\Windows\assembly\GAC_MSIL\System.Xml\2.0.0.0__b77a5c561934e089\System.Xml.dll
    
    
    PS C:\Users\troll> [System.Xml.XmlConvert]::ToTimeSpan("P1M")
    
    
    Days              : 30
    Hours             : 0
    Minutes           : 0
    Seconds           : 0
    Milliseconds      : 0
    Ticks             : 25920000000000
    TotalDays         : 30
    TotalHours        : 720
    TotalMinutes      : 43200
    TotalSeconds      : 2592000
    TotalMilliseconds : 2592000000
    
    
    
    PS C:\Users\troll> [System.Xml.XmlConvert]::ToTimeSpan("P1Y")
    
    
    Days              : 365
    Hours             : 0
    Minutes           : 0
    Seconds           : 0
    Milliseconds      : 0
    Ticks             : 315360000000000
    TotalDays         : 365
    TotalHours        : 8760
    TotalMinutes      : 525600
    TotalSeconds      : 31536000
    TotalMilliseconds : 31536000000
    
    
    
    PS C:\Users\troll>
    

提交回复
热议问题