Как я могу отформатировать nullable DateTime с помощью ToString ()?
Как я могу преобразовать nullable DateTime dt2 в форматированную строку?
DateTime dt = DateTime.Now;
Console.WriteLine(dt.ToString("yyyy-MM-dd hh:mm:ss")); //works
DateTime? dt2 = DateTime.Now;
Console.WriteLine(dt2.ToString("yyyy-MM-dd hh:mm:ss")); //gives following error:
нет перегрузки для метода ToString принимает
один аргумент
20 ответов:
Console.WriteLine(dt2 != null ? dt2.Value.ToString("yyyy-MM-dd hh:mm:ss") : "n/a");EDIT: как указано в других комментариях, проверьте, что есть ненулевое значение.
обновление: как рекомендовано в комментариях, метод расширения:
public static string ToString(this DateTime? dt, string format) => dt == null ? "n/a" : ((DateTime)dt).ToString(format);и начиная с C# 6, Вы можете использовать оператор чтобы упростить код еще больше. Приведенное ниже выражение вернет null, если
DateTime?имеет значение null.dt2?.ToString("yyyy-MM-dd hh:mm:ss")
Попробуй вот это:
фактический объект dateTime, который вы хотите отформатировать, находится в dt.Значение свойства, а не на самом объекте dt2.
DateTime? dt2 = DateTime.Now; Console.WriteLine(dt2.HasValue ? dt2.Value.ToString("yyyy-MM-dd hh:mm:ss") : "[N/A]");
Как заявили другие, вам нужно проверить значение null перед вызовом ToString, но чтобы избежать повторения, вы можете создать метод расширения, который это делает, что-то вроде:
public static class DateTimeExtensions { public static string ToStringOrDefault(this DateTime? source, string format, string defaultValue) { if (source != null) { return source.Value.ToString(format); } else { return String.IsNullOrEmpty(defaultValue) ? String.Empty : defaultValue; } } public static string ToStringOrDefault(this DateTime? source, string format) { return ToStringOrDefault(source, format, null); } }, который может быть вызван как:
DateTime? dt = DateTime.Now; dt.ToStringOrDefault("yyyy-MM-dd hh:mm:ss"); dt.ToStringOrDefault("yyyy-MM-dd hh:mm:ss", "n/a"); dt = null; dt.ToStringOrDefault("yyyy-MM-dd hh:mm:ss", "n/a") //outputs 'n/a'
вы, ребята, над инженерии все это и делает его более сложным, чем это на самом деле. Важно, прекратите использовать ToString и начните использовать форматирование строк, например string.Формат или методы, поддерживающие форматирование строк, например Console.метод WriteLine. Вот предпочтительное решение этого вопроса. Это тоже самое безопасное.
DateTime? dt1 = DateTime.Now; DateTime? dt2 = null; Console.WriteLine("'{0:yyyy-MM-dd hh:mm:ss}'", dt1); Console.WriteLine("'{0:yyyy-MM-dd hh:mm:ss}'", dt2);вывод: (я помещаю в него одинарные кавычки, чтобы вы могли видеть, что он возвращается как пустая строка, когда null)
'2014-01-22 09:41:32' ''
проблема с формулировкой ответа на этот вопрос заключается в том, что вы не указываете желаемый результат, когда nullable datetime не имеет значения. Следующий код выведет
DateTime.MinValueв таком случае, и в отличие от принятых в настоящее время ответа, не исключение.dt2.GetValueOrDefault().ToString(format);
видя, что вы действительно хотите предоставить формат, я бы предложил добавить интерфейс IFormattable в метод расширения Smalls, например, таким образом, чтобы у вас не было неприятной конкатенации строкового формата.
public static string ToString<T>(this T? variable, string format, string nullValue = null) where T: struct, IFormattable { return (variable.HasValue) ? variable.Value.ToString(format, null) : nullValue; //variable was null so return this value instead }
можно использовать
dt2.Value.ToString("format"), но, конечно, это требует, что dt2 != null, и это в первую очередь отрицает использование типа nullable.есть несколько решений, но большой вопрос: Как вы хотите отформатировать
nullдата?
вот более общий подход. Это позволит вам форматировать строки любого типа значения с нулевым значением. Я включил второй метод, чтобы разрешить переопределение строкового значения по умолчанию вместо использования значения по умолчанию для типа значения.
public static class ExtensionMethods { public static string ToString<T>(this Nullable<T> nullable, string format) where T : struct { return String.Format("{0:" + format + "}", nullable.GetValueOrDefault()); } public static string ToString<T>(this Nullable<T> nullable, string format, string defaultValue) where T : struct { if (nullable.HasValue) { return String.Format("{0:" + format + "}", nullable.Value); } return defaultValue; } }
короткий ответ
$"{dt:yyyy-MM-dd hh:mm:ss}"тесты
DateTime dt1 = DateTime.Now; Console.Write("Test 1: "); Console.WriteLine($"{dt1:yyyy-MM-dd hh:mm:ss}"); //works DateTime? dt2 = DateTime.Now; Console.Write("Test 2: "); Console.WriteLine($"{dt2:yyyy-MM-dd hh:mm:ss}"); //Works DateTime? dt3 = null; Console.Write("Test 3: "); Console.WriteLine($"{dt3:yyyy-MM-dd hh:mm:ss}"); //Works - Returns empty string Output Test 1: 2017-08-03 12:38:57 Test 2: 2017-08-03 12:38:57 Test 3:
Я думаю, что вы должны использовать GetValueOrDefault-Methode. Поведение с ToString ("yy...") не определяется, если экземпляр имеет значение null.
dt2.GetValueOrDefault().ToString("yyy...");
IFormattable также включает в себя поставщик формата, который может быть использован, он позволяет как формат IFormatProvider быть null в dotnet 4.0 это будет
/// <summary> /// Extentionclass for a nullable structs /// </summary> public static class NullableStructExtensions { /// <summary> /// Formats a nullable struct /// </summary> /// <param name="source"></param> /// <param name="format">The format string /// If <c>null</c> use the default format defined for the type of the IFormattable implementation.</param> /// <param name="provider">The format provider /// If <c>null</c> the default provider is used</param> /// <param name="defaultValue">The string to show when the source is <c>null</c>. /// If <c>null</c> an empty string is returned</param> /// <returns>The formatted string or the default value if the source is <c>null</c></returns> public static string ToString<T>(this T? source, string format = null, IFormatProvider provider = null, string defaultValue = null) where T : struct, IFormattable { return source.HasValue ? source.Value.ToString(format, provider) : (String.IsNullOrEmpty(defaultValue) ? String.Empty : defaultValue); } }используя вместе с именованными параметрами вы можете сделать:
dt2.ToString(defaultValue: "n/a");
в старых версиях dotnet вы получаете много перегрузок
/// <summary> /// Extentionclass for a nullable structs /// </summary> public static class NullableStructExtensions { /// <summary> /// Formats a nullable struct /// </summary> /// <param name="source"></param> /// <param name="format">The format string /// If <c>null</c> use the default format defined for the type of the IFormattable implementation.</param> /// <param name="provider">The format provider /// If <c>null</c> the default provider is used</param> /// <param name="defaultValue">The string to show when the source is <c>null</c>. /// If <c>null</c> an empty string is returned</param> /// <returns>The formatted string or the default value if the source is <c>null</c></returns> public static string ToString<T>(this T? source, string format, IFormatProvider provider, string defaultValue) where T : struct, IFormattable { return source.HasValue ? source.Value.ToString(format, provider) : (String.IsNullOrEmpty(defaultValue) ? String.Empty : defaultValue); } /// <summary> /// Formats a nullable struct /// </summary> /// <param name="source"></param> /// <param name="format">The format string /// If <c>null</c> use the default format defined for the type of the IFormattable implementation.</param> /// <param name="defaultValue">The string to show when the source is null. If <c>null</c> an empty string is returned</param> /// <returns>The formatted string or the default value if the source is <c>null</c></returns> public static string ToString<T>(this T? source, string format, string defaultValue) where T : struct, IFormattable { return ToString(source, format, null, defaultValue); } /// <summary> /// Formats a nullable struct /// </summary> /// <param name="source"></param> /// <param name="format">The format string /// If <c>null</c> use the default format defined for the type of the IFormattable implementation.</param> /// <param name="provider">The format provider (if <c>null</c> the default provider is used)</param> /// <returns>The formatted string or an empty string if the source is <c>null</c></returns> public static string ToString<T>(this T? source, string format, IFormatProvider provider) where T : struct, IFormattable { return ToString(source, format, provider, null); } /// <summary> /// Formats a nullable struct or returns an empty string /// </summary> /// <param name="source"></param> /// <param name="format">The format string /// If <c>null</c> use the default format defined for the type of the IFormattable implementation.</param> /// <returns>The formatted string or an empty string if the source is null</returns> public static string ToString<T>(this T? source, string format) where T : struct, IFormattable { return ToString(source, format, null, null); } /// <summary> /// Formats a nullable struct /// </summary> /// <param name="source"></param> /// <param name="provider">The format provider (if <c>null</c> the default provider is used)</param> /// <param name="defaultValue">The string to show when the source is <c>null</c>. If <c>null</c> an empty string is returned</param> /// <returns>The formatted string or the default value if the source is <c>null</c></returns> public static string ToString<T>(this T? source, IFormatProvider provider, string defaultValue) where T : struct, IFormattable { return ToString(source, null, provider, defaultValue); } /// <summary> /// Formats a nullable struct or returns an empty string /// </summary> /// <param name="source"></param> /// <param name="provider">The format provider (if <c>null</c> the default provider is used)</param> /// <returns>The formatted string or an empty string if the source is <c>null</c></returns> public static string ToString<T>(this T? source, IFormatProvider provider) where T : struct, IFormattable { return ToString(source, null, provider, null); } /// <summary> /// Formats a nullable struct or returns an empty string /// </summary> /// <param name="source"></param> /// <returns>The formatted string or an empty string if the source is <c>null</c></returns> public static string ToString<T>(this T? source) where T : struct, IFormattable { return ToString(source, null, null, null); } }
здесь отличный ответ Блейка как метод расширения. Добавьте это в свой проект, и вызовы в вопросе будут работать так, как ожидалось.
Это означает, что он используется какMyNullableDateTime.ToString("dd/MM/yyyy"), с тем же выходом, что иMyDateTime.ToString("dd/MM/yyyy"), за исключением того, что значение будет"N/A"Если DateTime имеет значение null.public static string ToString(this DateTime? date, string format) { return date != null ? date.Value.ToString(format) : "N/A"; }
простые универсальные расширения
public static class Extensions { /// <summary> /// Generic method for format nullable values /// </summary> /// <returns>Formated value or defaultValue</returns> public static string ToString<T>(this Nullable<T> nullable, string format, string defaultValue = null) where T : struct { if (nullable.HasValue) { return String.Format("{0:" + format + "}", nullable.Value); } return defaultValue; } }
может быть, это поздний ответ, но может помочь кому-то еще.
просто:
nullabledatevariable.Value.Date.ToString("d")или просто использовать любой формат, а не "д".
лучшие
Comments