我有这样的字符串:如何从此字符串中获取日期?
\tid <[email protected]>; <b>Tue, 6 Oct 2009 15:38:16</b> +0100
,我想的日期(底气)提取到一个更可用的格式,例如06-10-2009 15:38:16
什么是最好的方式去做这件事?
我有这样的字符串:如何从此字符串中获取日期?
\tid <[email protected]>; <b>Tue, 6 Oct 2009 15:38:16</b> +0100
,我想的日期(底气)提取到一个更可用的格式,例如06-10-2009 15:38:16
什么是最好的方式去做这件事?
正则表达式可能会矫枉过正。只需拆分';',Trim()
,并致电Date.Parse(...)
, 它甚至会为您处理时区偏移量。
using System;
namespace ConsoleImpersonate
{
class Program
{
static void Main(string[] args)
{
string str = "\tid [email protected]; Tue, 6 Oct 2009 15:38:16 +0100";
var trimmed = str.Split(';')[1].Trim();
var x = DateTime.Parse(trimmed);
}
}
}
这样做 - 是obv认为它比它更困难 - 谢谢! leddy – leddy 2009-10-07 16:14:40
永远记住伟大的杰米Zawinski:有些人,当遇到问题时,认为“我知道,我会用正则表达式。”现在他们有两个问题。 – 2011-08-21 16:53:22
你可以试试这个代码(可能调整)
Regex regex = new Regex(
";(?<date>.+?)",
RegexOptions.IgnoreCase
| RegexOptions.CultureInvariant
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
var dt=DateTime.Parse(regex.Match(inputString).Groups["date"].Value)
这里有一个正则表达式的方法相匹配的格式。日期结果按照您的指定格式化。
string input = @"\tid [email protected]; Tue, 6 Oct 2009 15:38:16 +0100";
// to capture offset too, add "\s+\+\d+" at the end of the pattern below
string pattern = @"[A-Z]+,\s+\d+\s+[A-Z]+\s+\d{4}\s+(?:\d+:){2}\d{2}";
Match match = Regex.Match(input, pattern, RegexOptions.IgnoreCase);
if (match.Success)
{
string result = match.Value.Dump();
DateTime parsedDateTime;
if (DateTime.TryParse(result, out parsedDateTime))
{
// successful parse, date is now in parsedDateTime
Console.WriteLine(parsedDateTime.ToString("dd-MM-yyyy hh:mm:ss"));
}
else
{
// parse failed, throw exception
}
}
else
{
// match not found, do something, throw exception
}
你想要+0100太 – leppie 2009-10-07 15:59:44