I have a number of XML nodes which output a datetime object as string.
The problem is that when outputting both the time stamp and the date they are bonded together with a T Character.
Here is an example
2016-01-13T23:59:59
Of course all of the nodes in the XML are of a different type so grouping by name or type is out of the question. Im thinking my only option is to match a pattern with regex and resolve the problem that way.
Below is an example of how the XML would work, you can see that each element is named as something different but they all follow a similar pattern, where the T between the date and the time must be removed and a space replaced instead.
<dates>
<1stDate> 2016-01-13T23:59:59 </1stdate>
<2ndDate> 2017-01-13T23:55:57 </2ndDate>
<3rdDate> 2018-01-13T23:22:19 </3rdDate>
</dates>
Ideal solution to output like this
2016-01-13 23:59:59
2017-01-13 23:55:57
2018-01-13 23:22:19
I havent had to use Regex before but i know what it is. I have been trying to decode what this cheat sheet means http://regexlib.com/CheatSheet.aspx?AspxAutoDetectCookieSupport=1 but to no avail.
UPDATE
//How each node is output
foreach (XText node in nodes)
{
node.Value = node.Value.Replace("T"," "); // Where a date occurs, replace T with space.
}
The <date>
elements provided in the example may contain dates in my XML but may not include the word date as a name.
e.g.
<Start> 2017-01-13T23:55:57 </start>
<End> 2018-01-13T23:22:19 </End>
<FirstDate> 2018-01-13T23:22:19 </FirstDate>
The main reason I would have liked a regex solution was because I need to match the date string with a pattern that can determine if its a date or not, then i can apply formatting.
Why not parse that (perfectly valid ISO-8601) date time into a DateTime
, and then use the built in string formatting to produce a presentable human readable date time?
if (!string.IsNullOrWhiteSpace(node.Value))
{
DateTime date;
if (DateTime.TryParseExact(node.Value.Trim(),
@"yyyy-MM-dd\THH:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal,
out date)
{
node.Value = date.ToString("yyyy-MM-dd HH:mm:ss");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With