[英]XSD Duration under .Net Core
我正在將代碼從.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()完全相同。
我最終創建了自己的函數實現:
// 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.