Hi,
I have this string:
\tid [email protected]; Tue, 6 Oct 2009 15:38:16 +0100
and I want to extract the date (emboldened) to a more usable format, e.g. 06-10-2009 15:38:16
What would be the best way to go about this?
thanks in advance
leddy
Hi,
I have this string:
\tid [email protected]; Tue, 6 Oct 2009 15:38:16 +0100
and I want to extract the date (emboldened) to a more usable format, e.g. 06-10-2009 15:38:16
What would be the best way to go about this?
thanks in advance
leddy
Regex might be overkill. Just Split on ';' Trim() and call Date.Parse(...) It will even handle the Timezone offset for you.
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);
}
}
}
HTH,
Jan
You can try this code (with possible adjustments)
Regex regex = new Regex(
";(?<date>.+?)",
RegexOptions.IgnoreCase
| RegexOptions.CultureInvariant
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
var dt=DateTime.Parse(regex.Match(inputString).Groups["date"].Value)
Here's a regex approach to match the format. The date result is formatted as you specified.
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
}