I'm on to convert the RFC1123-dateformat to DateTime-Object and vice versa. The DateTime-Object to RFC-date-string works perfectly but since I'm living in Germany (MEZ- Timezone) I get wrong results.
So once, here is my class for converting:
public interface IRFCDate
{
DateTime ToDateTime();
}
public class RFCDate : IRFCDate
{
private string dateString { get; set; } = null;
private DateTime? dateObject { get; set; } = null;
public DateTime ToDateTime()
{
if (dateObject.HasValue) return dateObject.Value;
string regexPattern = @"[a-zA-Z]+, [0-9]+ [a-zA-Z]+ [0-9]+ [0-9]+:[0-9]+:[0-9]+ (?<timezone>[a-zA-Z]+)";
Regex findTimezone = new Regex(regexPattern, RegexOptions.Compiled);
string timezone = findTimezone.Match(dateString).Result("${timezone}");
string format = $"ddd, dd MMM yyyy HH:mm:ss {timezone}";
dateObject = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);
return dateObject.Value;
}
public IRFCDate From(IConvertible value)
{
if (value is string)
dateString = value.ToString();
else if (value is DateTime)
dateObject = (DateTime)value;
else
throw new NotSupportedException($"Parametertype has to be either string or DateTime. '{value.GetType()}' is unsupported.");
return this;
}
}
my Xunit-Testcase looks like this:
[Fact]
public void StringToDateTime()
{
DateTime expectedValue = new DateTime(2001, 1, 1);
string RFCDatestring = "Mon, 01 Jan 2001 00:00:00 GMT";
DateTime actualValue = RFCDatestring.To<DateTime>();
Assert.Equal(expectedValue, actualValue);
}
To in this case calls
return new RFCDate().From(@this).ToDateTime();
So the result when executing my testcase is:
Assert.Equal() Failure
Expected: 2001-01-01T00:00:00.0000000
Actual: 2001-01-01T01:00:00.0000000+01:00
Someone has any ideas how to fix this? The actual value should be 00:00 o'clock instead of 1 o'clock.
Okay I seen that I made a mistake: I need to set the timezone to CET
instead of GMT
, since I'm in Germany which is CET (or GMT+1).
So the function is correct.