【问题标题】:Convert TimeSpan.TotalMilliseconds to datetime and format it as hour:minute将 TimeSpan.TotalMilliseconds 转换为日期时间并将其格式化为小时:分钟
【发布时间】:2012-10-24 21:20:20
【问题描述】:

我对日期时间转换有点困惑

在我定义的模型中

    public DateTime? Sent { get; set; }
    public DateTime? Reply { get; set; }
    public double ResponseTime { get; set; }

在 linq 部分我正在使用

ResponseTime = (u.Reply - u.sent).TotalMilliseconds

不是这样格式化和显示的979809803

我想知道如何将其转换为日期时间格式,并最终将格式显示为小时:分钟,例如发送日期和回复日期之间的 2:45。

【问题讨论】:

    标签: c# linq date kendo-ui datetime-format


    【解决方案1】:

    只需返回TimeSpan 并致电.ToString("hh:mm")

    TimeSpan.ToString

    public TimeSpan ResponseTime { get; set; }
    
    //usage in LINQ
    ResponseTime = (u.Reply - u.Sent)
    

    显示时...

    value.ResponseTime.ToString("hh:mm")
    

    【讨论】:

    • 我只是测试它,它不会工作,还是我错过了一些重要的东西?
    • 另外,如果我将 ResponseTime 的数据类型更改为 TimeSpan,它会抛出类似“无法在“int”到时间跨度之间转换的错误
    • 您必须将对 ResponseTime 的现有引用更改为 value.ResponseTime.TotalMilliseconds
    【解决方案2】:

    从 DateTime 中减去 DateTime 会产生 TimeSpan。查看TimeSpan.ToString Method (String),了解如何自定义格式值。

    您可以将 ResponseTime 更改回 TimeSpan 并从那里更改为字符串。

    TimeSpan ResponseTimeSpan = new TimeSpan(0, 0, 0, (int)ResponseTime);
    
    string ResponseTimeDisplay = ResponseTimeSpan.ToString();
    

    【讨论】:

    • 很抱歉,ResponseTime 数据类型设置为双倍,所以既然不是时间跨度,我该如何改回日期时间?对不起,如果我混淆了你!
    • 您不能将其更改为 DateTime,但您可以将其更改为 TimeSpan。
    • 好吧,我可以最初将响应时间设置为数据类型时间跨度会更好吗?
    • 另外,如果我将 ResponseTime 的数据类型更改为 TimeSpan,它会抛出类似“无法在“int”到时间跨度之间转换的错误
    • 是的,对不起。您需要转换为 int。不幸的是,TotalMilliseconds 的小数部分将被丢弃。如果您不想在此过程中丢失精度,将 ResponseTime 保留为 TimeSpan 并根据需要进行转换可能是有意义的。
    猜你喜欢
    • 2012-10-28
    • 1970-01-01
    • 2012-10-19
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多