【问题标题】:Formatting subtracted dates c#格式化减去的日期c#
【发布时间】:2012-10-09 09:10:10
【问题描述】:

我试图在 c# 中将两个日期相减。我当前的代码如下所示:

protected void Page_Load(object sender, EventArgs e)
{
    System.DateTime matchStart = new System.DateTime(2012, 10, 17, 20, 00, 00);
    System.DateTime currentDateTime = new System.DateTime(2012, 10, 9, 14, 00, 00);

    System.TimeSpan matchCountdown = matchStart.Subtract(currentDateTime);

    countdown.Text = matchCountdown.ToString();
}

这目前给了我结果“8.06:00:00”。然而,我想要做的是将时差格式化为“8 天,6 小时,0 分钟”。我到底该怎么做呢?

非常感谢任何帮助!

【问题讨论】:

标签: c# datetime formatting


【解决方案1】:

您可以使用String.Format 和TimeSpan properties。

String.Format("{0} days, {1} hours, {2} minutes"
    , matchCountdown.Days
    , matchCountdown.Hours
    , matchCountdown.Minutes); 

这是演示:http://ideone.com/i8SKX

【讨论】:

  • 需要截断那些双打。
  • @spender 同意,应该是"{0:n0} days, {1:n0} hours, {2:n0} minutes"
  • @spender:上面TimeSpan.Days等属性都是ints。有a look。
猜你喜欢
  • 1970-01-01
  • 2020-01-14
  • 2015-06-21
  • 1970-01-01
  • 1970-01-01
  • 2016-06-09
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
相关资源
最近更新 更多