How to exclude seconds from DateTime.ToString()
I am using DateTime.Now.ToString() in a windows service and it is giving me output like "7/23/2010 12:35:07 PM " I want to exclude the second part,开发者_运维百科 displaying only up to minute.
So how to exclude seconds from that format...?
Output it as short date pattern:
DateTime.Now.ToString("g")
See MSDN for full documentation.
You need to pass in a format string to the ToString()
function:
DateTime.Now.ToString("g")
This option is culture aware.
For this kind of output you could also use a custom format string, if you want full control:
DateTime.Now.ToString("MM/dd/yyyy hh:mm")
This will output exactly the same regardless of culture.
You could use a format:
DateTime.Now.ToString("MM/dd/yyyy hh:mm tt");
please test:
DateTime.Now.ToString("MM/dd/yyyy hh:mm");
You might want to do something like DateTime.Now.ToString("M/d/yyyy hh:mm");
for more information look at Custom Date and Time Format Strings
If you want to stay language independent, you could use the following code (maybe in an IValueConverter (see second code snippet)) to remove only the seconds part from the string:
int index = dateTimeString.LastIndexOf(':');
if (index > -1) {
dateTimeString = dateTimeString.Remove(index, 3);
}
Here's an implementation of the converter.
[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
}
}
You can also use it in XAML as a markup extension:
<TextBlock Text="{Binding CreationTimestamp, Converter={local:DateTimeToStringConverter DisplayStyle=DateAndTime, DisplaySeconds=False}}" />
Try DateTime.Now.ToShortDateString() + " " + DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString()
精彩评论