简体   繁体   English

如何在C#中创建一个描述性的DateConverter?

[英]How do I create a Descriptive DateConverter in C#?

I have a DateConverter class that does all the basics. 我有一个DateConverter类,可以完成所有基础操作。 However, I want to add another type to it. 但是,我想添加另一种类型。 I want to be able to have a 'Descriptive' type that returns the difference between the date and DateTime.Now formatted as a string. 我希望能够有一个'描述性'类型,该类型返回日期和DateTime.Now之间的差异,格式为字符串。

IE: "seconds ago", "7 minutes ago", "8 hours ago" IE:“秒前”,“ 7分钟前”,“ 8小时前”

Whichever the larger increment is. 以较大的增量为准。

I suppose the only thing I am missing is figuring out how to get the difference between the two dates in seconds. 我想我唯一想念的就是弄清楚如何以秒为单位获得两个日期之间的差。 C# is still a little new to me. C#对我来说还是个新手。

you can subtract two datetime objects and it will return TimeSpan and you can get Seconds property of TimeSpan 您可以减去两个datetime对象,它将返回TimeSpan并且可以获得TimeSpan的Seconds属性

var timespan = (datetime1 - datetime2);
var seconds = timespan.Seconds;
var Minutes = timespan.Minutes;
var hours = timespan.Hours;

I suppose the only thing I am missing is figuring out how to get the difference between the two dates in seconds. 我想我唯一想念的就是弄清楚如何以秒为单位获得两个日期之间的差。

then you want timespan.TotalSeconds 那么你需要timespan.TotalSeconds

what about using an extension method instead, like 那如何使用扩展方法呢?

public static string FromNowFormatted(this DateTime date)
{
    var sb = new StringBuilder();

    var t = DateTime.Now - date;

    var dic = new Dictionary<string, int>
              {
                  {"years", (int)(t.Days / 365)},
                  {"months", (int)(t.Days / 12)},
                  {"days", t.Days},
                  {"hours", t.Hours},
                  {"minutes", t.Minutes},
                  {"seconds", t.Seconds},
              };

    bool b = false;
    foreach (var e in dic)
    {                
        if (e.Value > 0 || b)
        {
            var v = e.Value;
            var k = v == 1 ? e.Key.TrimEnd('s') : e.Key ;

            sb.Append(v + " " + k + "\n");
            b = true;
        }
    }

    return sb.ToString();
}

demo 演示

Note: there are some things with this code you'll need to fix-up such as the ways years and months are calculated. 注意:您需要修正此代码中的某些内容,例如年和月的计算方式。

Edit: you could use Noda Time's Period.Between() which calculates the difference and then just have an extension method as above, that would simply format it in a similar way. 编辑:您可以使用Noda Time的Period.Between()计算差值,然后使用上述扩展方法,以类似的方式对其进行格式化。 see the secion "Finding a period between two values" here for more info. 有关更多信息,请参见此处的“ 两个值之间找到一个周期”部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM