我有這樣的字符串:如何從此字符串中獲取日期?
\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