简体   繁体   English

.Net Core下的XSD持续时间

[英]XSD Duration under .Net Core

I am porting code from .Net Framework to .Net Core 2.1 and have issues with porting SoapDuration class under System.Runtime.Remoting.Metadata.W3cXsd2001. 我正在将代码从.Net Framework移植到.Net Core 2.1,并且在System.Runtime.Remoting.Metadata.W3cXsd2001下移植SoapDuration类时遇到问题。 I tried to replace the logic with System.Xml.XmlConvert but it returns not the same format of XSD duration. 我试图用System.Xml.XmlConvert替换逻辑,但是它返回的XSD持续时间格式不同。

.Net Framework 4.0: .Net Framework 4.0:

SoapDuration.ToString(new TimeSpan(1, 0, 0)); 
// returns "P0Y0M0DT1H0M0S"

.Net Core 2.1: .Net Core 2.1:

XmlConvert.ToString(new TimeSpan(1, 0, 0));
// returns "PT1H"

I was thinking about writing a conversion method but it would need to behave exact the same as SoapDuration.ToString(). 我正在考虑编写一种转换方法,但它的行为必须与SoapDuration.ToString()完全相同。

I ended up creating an own implementation of the function: 我最终创建了自己的函数实现:

// calcuate carryover points by ISO 8601 : 1998 section 5.5.3.2.1 Alternate format
// algorithm not to exceed 12 months, 30 day
// note with this algorithm year has 360 days.
private static void CarryOver(int inDays, out int years, out int months, out int days)
{
    years = inDays / 360;
    int yearDays = years * 360;
    months = Math.Max(0, inDays - yearDays) / 30;
    int monthDays = months * 30;
    days = Math.Max(0, inDays - (yearDays + monthDays));
    days = inDays % 30;
}        

public static string ToSoapString(this TimeSpan timeSpan)
{
    StringBuilder sb = new StringBuilder(20)
    {
        Length = 0
    };
    if (TimeSpan.Compare(timeSpan, TimeSpan.Zero) < 1)
    {
        sb.Append('-');
    }

    CarryOver(Math.Abs(timeSpan.Days), out int years, out int months, out int days);

    sb.Append('P');
    sb.Append(years);
    sb.Append('Y');
    sb.Append(months);
    sb.Append('M');
    sb.Append(days);
    sb.Append("DT");
    sb.Append(Math.Abs(timeSpan.Hours));
    sb.Append('H');
    sb.Append(Math.Abs(timeSpan.Minutes));
    sb.Append('M');
    sb.Append(Math.Abs(timeSpan.Seconds));
    long timea = Math.Abs(timeSpan.Ticks % TimeSpan.TicksPerDay);
    int t1 = (int)(timea % TimeSpan.TicksPerSecond);
    if (t1 != 0)
    {
        string t2 = t1.ToString("D7");
        sb.Append('.');
        sb.Append(t2);
    }
    sb.Append('S');
    return sb.ToString();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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