【问题标题】:DateTime not adding time - Strange issueDateTime 不添加时间 - 奇怪的问题
【发布时间】:2022-01-18 13:59:52
【问题描述】:

有这行代码:

DateTime inFutureDateTime = DateTime.Now.AddSeconds(60);

并像这样在(Unity)控制台中编写

Debug.Log("In future date time " + inFutureDateTime.Date)

输出:

12/15/2021 12:00:00 AM

日期正确(今天),但时间不正确。它应该是 CurrentTime + 60 秒。

我做错了什么,或者我误解了 DateTime 的工作原理。

提前致谢

【问题讨论】:

  • 表达式inFutureDateTime.Date总是在午夜返回DateTime。如果你想要时间部分,不要使用.Date...
  • docs.microsoft.com/en-us/dotnet/api/… "与此实例具有相同日期的新对象,时间值设置为午夜 12:00:00 (00:00:00)。"
  • Debug.Log($"In future date time {inFutureDateTime:MM/dd/yyyy HH:mm:ss}");

标签: c# unity3d


【解决方案1】:

而不是.Date,尝试调用.ToLongDateString(),就像Debug.Log("In future date time "+inFutureDateTime.ToLongDateString())一样

【讨论】:

    【解决方案2】:

    .Date 是仅用于 Date 的持有者。

    不幸的是,当转换为字符串时,它也会显示一个时间分量。

    默认 ToString 或其替代项之一将显示完整的日期时间:

    Debug.Log("In future date time " + inFutureDateTime)
    

    【讨论】:

      【解决方案3】:

      问题的根源在于.Date:它返回初始DateTime 值的日期部分 (注意,时间部分0:0:0.000)。我建议在你可以指定的地方使用 string interpolation 文本、变量、它们的格式等。

       // Here we specify the required format - MM/dd/yyyy HH:mm:ss
       Debug.Log($"In future date time {inFutureDateTime:MM/dd/yyyy HH:mm:ss}");
      

      如果你想使用默认格式(来自CultureInfo.CurrentCulture):

       Debug.Log($"In future date time {inFutureDateTime}");
      

      【讨论】:

        【解决方案4】:

        日期返回组件日期不是日期格式标准。请参阅以下方法:

        DateTime inFutureDateTime = DateTime.Now.AddSeconds(60); 
        
        Debug.Log("In future date time " + inFutureDateTime.Date.ToLongDateString());
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-11-25
          • 2016-04-01
          • 1970-01-01
          • 2012-04-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多