首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将日期时间格式从RFC1123转换为日期时间对象

将日期时间格式从RFC1123转换为日期时间对象
EN

Stack Overflow用户
提问于 2016-03-19 21:57:14
回答 1查看 1.1K关注 0票数 1

我将把and 1123-dateformat转换为DateTime对象,反之亦然。RFC-日期-字符串的DateTime对象工作得很好,但是由于我生活在德国(MEZ- Timezone),我得到了错误的结果。

因此,有一次,这里是我的转换类:

代码语言:javascript
复制
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;
    }
}

我的Xunit-Testcase如下所示:

代码语言:javascript
复制
[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); 
}

在这种情况下调用

代码语言:javascript
复制
return new RFCDate().From(@this).ToDateTime();

因此,在执行我的测试案例时,结果是:

Assert.Equal()故障 预计: 2001-01-01T00:00:00.0000000 实际: 2001-01-01T01:00:00.0000000+01:00

有人有办法解决这个问题吗?实际值应该是00:00而不是1点。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-12-18 08:54:40

好的,我看到我犯了一个错误:我需要将时区设置为CET,而不是GMT,因为我在德国,也就是CET (或GMT+1)。所以这个函数是正确的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36107690

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档