格式化长日期时间字符串以删除 T 字符

Formatting long datetime string to remove T character

我有许多 XML 节点将日期时间对象输出为字符串。

问题是,当输出时间戳和日期时,它们与 T 字符绑定在一起。

这是一个例子

2016-01-13T23:59:59

当然 XML 中的所有节点都是不同类型的,因此按名称或类型分组是不可能的。我认为我唯一的选择是将模式与正则表达式匹配并以这种方式解决问题。

下面是 XML 如何工作的示例,您可以看到每个元素的名称都不同,但它们都遵循相似的模式,其中日期和时间之间的 T 必须是删除并替换为 space。

<dates>
    <1stDate> 2016-01-13T23:59:59 </1stdate>
    <2ndDate> 2017-01-13T23:55:57 </2ndDate>
    <3rdDate> 2018-01-13T23:22:19 </3rdDate>
</dates>

这样输出的理想方案

2016-01-13 23:59:59 
2017-01-13 23:55:57 
2018-01-13 23:22:19

我以前没用过正则表达式,但我知道它是什么。我一直在尝试破解这个作弊 sheet 的意思 http://regexlib.com/CheatSheet.aspx?AspxAutoDetectCookieSupport=1 但无济于事。

更新

//How each node is output
foreach (XText node in nodes)
{
    node.Value = node.Value.Replace("T"," "); // Where a date occurs, replace T with space. 
}

示例中提供的 <date> 元素可能在我的 XML 中包含日期,但可能不包含日期一词作为名称。

例如

<Start>  2017-01-13T23:55:57  </start>
<End>    2018-01-13T23:22:19  </End>
<FirstDate> 2018-01-13T23:22:19 </FirstDate>

我喜欢正则表达式解决方案的主要原因是我需要将日期字符串与可以确定其是否为日期的模式相匹配,然后我可以应用格式。

我会使用:

if (DateTime.TryParse(yourString))
{
     yourString.Replace("T", " ");
}

编辑

如果您只想像我认为您在 UPDATE 中建议的那样替换字母 "T" 的第一个实例。您可以使用此扩展方法:

public static string ReplaceFirst(this string text, string search, string replace)
{
   int pos = text.IndexOf(search);
   if (pos < 0)
   {
      return text;
   }
   return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
 }

你会像这样使用它:

yourString.ReplaceFirst("T", " ");

为什么不将该(完全有效的 ISO-8601)日期时间解析为 DateTime,然后使用内置的字符串格式来生成可呈现的人类可读日期时间?

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");
    }
}

如果您仍想使用正则表达式执行此操作,则以下表达式应该可以解决问题:

# Positive lookbehind for date part which consists of numbers and dashes
(?<=[0-9-]+)
# Match the T in between
T
# Positive lookahead for time part which consists of numbers and colons
(?=[0-9:]+)

编辑

上面的正则表达式 NOT 检查字符串是否为 date/time 格式。这是一个通用模式。要为您的字符串强加格式,请使用此模式:

# Positive lookbehind for date part
(?<=\d{4}(-\d{2}){2})
# Match the T
T
# Positive lookahead for time part
(?=\d{2}(:\d{2}){2})

同样,这将完全匹配您拥有的字符串,但您应该 使用它来验证 date/time 值,因为它将匹配无效日期,例如 2015-15-10T24:12:10;要验证 date/time 值,请使用 DateTime.Parse()DateTime.TryParse() 方法。