【问题标题】:c# show only Time portion of DateTimec# 仅显示 DateTime 的时间部分
【发布时间】:2012-02-01 20:20:56
【问题描述】:

我的日期显示为 2011 年 10 月 18 日下午 3:12:33

如何仅获取此日期时间的时间部分?

我正在使用 C#。

我试过了:

      string timeval = PgTime.ToShortTimeString();

但这不起作用,因为 Intellisense 只显示 ToString();

【问题讨论】:

标签: c#


【解决方案1】:

假设

DateTime PgTime;

你可以:

String timeOnly = PgTime.ToString("t");

其他格式选项can be viewed on MSDN

另外,如果你想将它组合成一个更大的字符串,你可以这样做:

// Instruct String.Format to parse it as time format using `{0:t}`
String.Format("The time is: {0:t}", PgTime);

// pass it an already-formatted string
String.Format("The time is: {0}", PgTime.ToString("t"));

如果PgTimeTimeSpan,则您有a few other options

TimeSpan PgTime;

String formattedTime = PgTime.ToString("c"); // 00:00:00 [TimeSpan.ToString()]
String formattedTime = PgTime.ToString("g"); // 0:00:00
String formattedTime = PgTime.ToString("G"); // 0:00:00:00.0000000

【讨论】:

【解决方案2】:

如果你想要一个格式化的字符串,只需使用.ToString(format),只指定时间部分。如果您想要实际时间,请使用.TimeOfDay,这将是午夜后的TimeSpan

【讨论】:

    【解决方案3】:
     DateTime test = DateTime.Now;
                MessageBox.Show(test.ToShortTimeString());
    

    仅产生 DateTimne 值的时间部分。 你能告诉我们 PgTime 是如何声明的吗?

    【讨论】:

      【解决方案4】:
      DateTime PgTime = new DateTime();
              var hr = PgTime.Hour;
              var min = PgTime.Minute;
              var sec = PgTime.Second;
      
              //or
      
              DateTime.Now.ToString("HH:mm:ss tt") gives it to you as a string.
      

      【讨论】:

        【解决方案5】:

        现在不要对名为PgTime 的类一无所知。不过,现在就做DateTime吧。

        试试

        DateTime instance = DateTime.Now           ; // current date/time
        string   time     = instance.ToString("t") ; // short time formatted according to the rules for the current culture/locale
        

        可能想了解Standard Date and Time Format StringsCustom Date and Time Format Strings

        【讨论】:

          【解决方案6】:

          C# 10 中,您可以使用TimeOnly

          TimeOnly date = TimeOnly.FromDateTime(PgTime);
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-06-04
            • 2011-01-18
            • 1970-01-01
            • 1970-01-01
            • 2011-05-14
            • 1970-01-01
            相关资源
            最近更新 更多