我正在一个Windows服务中使用DateTime.Now.ToString(),它给我输出的结果是"7/23/2010 12:35:07 PM"。我想要排除秒部分,只显示到分钟。
那么如何从这个格式中排除秒呢?
那么如何从这个格式中排除秒呢?
请测试:
DateTime.Now.ToString("MM/dd/yyyy hh:mm");
如果您想保持语言无关性,可以使用以下代码(也许在IValueConverter(请参见第二个代码片段)中)仅从字符串中删除秒部分:
int index = dateTimeString.LastIndexOf(':');
if (index > -1) {
dateTimeString = dateTimeString.Remove(index, 3);
}
[ValueConversion(typeof(DateTime), typeof(string))]
public class DateTimeToStringConverter : Markup.MarkupExtension, IValueConverter {
public DateTimeToStringConverter() : base() {
DisplayStyle = Kind.DateAndTime;
DisplaySeconds = true;
}
#region IValueConverter
public object Convert(object value, Type targetType, object parameter, Globalization.CultureInfo culture) {
if (value == null) return string.Empty;
if (!value is DateTime) throw new ArgumentException("The value's type has to be DateTime.", "value");
DateTime dateTime = (DateTime)value;
string returnValue = string.Empty;
switch (DisplayStyle) {
case Kind.Date:
returnValue = dateTime.ToShortDateString();
break;
case Kind.Time:
returnValue = dateTime.ToLongTimeString();
break;
case Kind.DateAndTime:
returnValue = dateTime.ToString();
break;
}
if (!DisplaySeconds) {
int index = returnValue.LastIndexOf(':');
if (index > -1) {
returnValue = returnValue.Remove(index, 3);
}
}
return returnValue;
}
public object ConvertBack(object value, Type targetType, object parameter, Globalization.CultureInfo culture) {
throw new NotSupportedException();
}
#endregion
public override object ProvideValue(IServiceProvider serviceProvider) {
return this;
}
#region Properties
public Kind DisplayStyle { get; set; }
public bool DisplaySeconds { get; set; }
#endregion
public enum Kind {
Date,
Time,
DateAndTime
}
}
你也可以在XAML中将其用作标记扩展:
<TextBlock Text="{Binding CreationTimestamp, Converter={local:DateTimeToStringConverter DisplayStyle=DateAndTime, DisplaySeconds=False}}" />
DateTime.Now.ToShortDateString() + " " + DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString()