C# 仅从日期时间显示时间

C# 仅从日期时间显示时间,c#,datetime,time,C#,Datetime,Time,我有我需要的DateTime字段格式,但问题是我无法找到一种方法,只能显示字段的Time元素 下面是我使用的语法 DateTime? fmtTimeOfDeparture; string TimeOfDeparture = null; IFormatProvider format = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat; fmtTimeOfDeparture = DateTime.ParseEx

我有我需要的
DateTime
字段格式,但问题是我无法找到一种方法,只能显示字段的
Time
元素

下面是我使用的语法

DateTime? fmtTimeOfDeparture;
string TimeOfDeparture = null;

IFormatProvider format = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat;
fmtTimeOfDeparture = DateTime.ParseExact((TimeOfDeparture != null ? TimeOfDeparture : null), "HHmmss", format);

Console.WriteLine(fmtTimeOfDeparture);
这将写入控制台:

01/11/2017 6:49:00 PM
我只想让它显示出来

6:49:00 PM

如何更新语法以仅显示此内容?

将日期时间转换为字符串需要另一种格式

DateTime? fmtTimeOfDeparture;
string TimeOfDeparture = "01/11/2017 6:49:00 PM";

IFormatProvider format = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat;
fmtTimeOfDeparture = DateTime.ParseExact((TimeOfDeparture ?? DateTme.Now.ToString()), "dd/mm/yyyy hh:mm:ss tt", format);

Console.WriteLine($"{fmtTimeOfDeparture:h:mm:ss tt}");

如果时间格式不适合您,请尝试使用string.trim删除替代解决方案的日期

如果要以
6:49:00 PM
格式编写,为什么需要
IFormatProvider

DateTime? fmtTimeOfDeparture = DateTime.Now;
Console.WriteLine(fmtTimeOfDeparture.HasValue ? fmtTimeOfDeparture.Value.ToString("HH:mm:ss tt") : "");
您所需要的就是:

DateTime? fmtTimeOfDeparture;

if( fmtTimeOfDeparture.HasValue ) {
   Console.WriteLine( fmtTimeOfDeparture.Value.ToString( "h:mm:ss tt" ) );
}

很明显,它不会写任何东西,因为
fmtTimeOfDeparture
是空的。

所以只需这样做:
Console.WriteLine(fmtTimeOfDeparture.ToString(“h:mm:ss tt”)。有关详细信息,请参阅。我将尝试“fmtTimeOfDeparture.Value.ToSortTimeString()'这就是我在搜索此问题时找到的答案。@Icemanind-产生参数1错误:无法从'string'转换为'System.IFormatProvider'@JamesJayson-产生错误'string'的方法不包含'Value'的定义,并且不能使用接受第一个参数'string'类型的扩展方法'Value'found@MichaelMormon抱歉,我没注意到它是可空的。试试这个:
Console.WriteLine(fmtTimeOfDeparture.Value.ToString(“h:mm:ss tt”)。仍然写入日期元素。@MichaelMormon您确定吗?顺便说一句,为什么字符串为null?它从API中读取,并将变量设置为等于API中的值,因此它可能为null。如果字符串为null,您希望放置什么?我把约会时间放进去了。现在。。。。如果字符串为空,请参阅运算符pr
??
将分配Datetime.Now.ToString。