This repository has been archived by the owner on Dec 24, 2022. It is now read-only.
/
TimeSpanConverter.cs
108 lines (91 loc) · 3.22 KB
/
TimeSpanConverter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
using System;
using System.Globalization;
using System.Text;
namespace ServiceStack.Text.Support
{
public class TimeSpanConverter
{
public static string ToXsdDuration(TimeSpan timeSpan)
{
var sb = new StringBuilder("P");
double ticks = timeSpan.Ticks;
double totalSeconds = ticks / TimeSpan.TicksPerSecond;
int wholeSeconds = (int) totalSeconds;
int seconds = wholeSeconds;
int sec = (seconds >= 60 ? seconds % 60 : seconds);
int min = (seconds = (seconds / 60)) >= 60 ? seconds % 60 : seconds;
int hours = (seconds = (seconds / 60)) >= 24 ? seconds % 24 : seconds;
int days = seconds / 24;
double remainingSecs = sec + (totalSeconds - wholeSeconds);
if (days > 0)
sb.Append(days + "D");
if (days == 0 || hours + min + sec + remainingSecs > 0)
{
sb.Append("T");
if (hours > 0)
sb.Append(hours + "H");
if (min > 0)
sb.Append(min + "M");
if (remainingSecs > 0)
{
var secFmt = string.Format("{0:0.0000000}", remainingSecs);
secFmt = secFmt.TrimEnd('0').TrimEnd('.');
sb.Append(secFmt + "S");
}
else if (sb.Length == 2) //PT
{
sb.Append("0S");
}
}
var xsdDuration = sb.ToString();
return xsdDuration;
}
public static TimeSpan FromXsdDuration(string xsdDuration)
{
int days = 0;
int hours = 0;
int minutes = 0;
double seconds = 0;
string[] t = xsdDuration.Substring(1).SplitOnFirst('T'); //strip P
var hasTime = t.Length == 2;
string[] d = t[0].SplitOnFirst('D');
if (d.Length == 2)
{
int day;
if (int.TryParse(d[0], out day))
days = day;
}
if (hasTime)
{
string[] h = t[1].SplitOnFirst('H');
if (h.Length == 2)
{
int hour;
if (int.TryParse(h[0], out hour))
hours = hour;
}
string[] m = h[h.Length - 1].SplitOnFirst('M');
if (m.Length == 2)
{
int min;
if (int.TryParse(m[0], out min))
minutes = min;
}
string[] s = m[m.Length - 1].SplitOnFirst('S');
if (s.Length == 2)
{
double millis;
if (double.TryParse(s[0], out millis))
seconds = millis;
}
}
double totalSecs = 0
+ (days * 24 * 60 * 60)
+ (hours * 60 * 60)
+ (minutes * 60)
+ (seconds);
var interval = (long) (totalSecs * TimeSpan.TicksPerSecond);
return TimeSpan.FromTicks(interval);
}
}
}