.Net Core下的XSD持续时间

问题描述 投票:0回答:1

我将.Net Framework中的代码移植到.Net Core 2.1,并且在System.Runtime.Remoting.Metadata.W3cXsd2001下移植SoapDuration类时遇到问题。我尝试用System.Xml.XmlConvert替换逻辑,但它返回的格式不同于XSD持续时间。

.Net Framework 4.0:

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

.Net Core 2.1:

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

我正在考虑编写转换方法,但它需要与SoapDuration.ToString()完全相同。

c# .net-core xsd remoting
1个回答
0
投票

我最终创建了一个自己的函数实现:

// 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();
}
© www.soinside.com 2019 - 2024. All rights reserved.