【问题标题】:XSD Duration under .Net Core.Net Core 下的 XSD 持续时间
【发布时间】:2019-02-11 12:17:45
【问题描述】:

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

.Net 框架 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】:

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

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

    【讨论】:

      猜你喜欢
      • 2016-10-15
      • 2021-11-10
      • 2020-09-24
      • 2018-05-06
      • 2010-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多