[英]Convert DateTime? to string
I want to convert a DateTime?
我想转换一个
DateTime?
to string.串起来。 If a date is null then return
""
, else return a string format like this: "2020-03-05T07:52:59.665Z"
.如果日期为空,则返回
""
,否则返回如下字符串格式: "2020-03-05T07:52:59.665Z"
。 The code is something like this but it won't work.代码是这样的,但它不起作用。 It said
"DateTime?"
它说
"DateTime?"
do not contain a definition for "ToUniversalTime".不包含“ToUniversalTime”的定义。 Someone know how to fix this?
有人知道如何解决这个问题吗?
DateTime? date = DateTime.UtcNow;
var dateInUTCString = date == null ? "" : date.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");
The DateTime?
DateTime?
have the Value
property and the HasValue
property有
Value
属性和HasValue
属性
Try:尝试:
var dateInUTCString = date.HasValue ? date.Value.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'") : "";
You can use a short version:您可以使用简短版本:
var dateInUTCString = date?.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'") ?? "";
While you can use the Value
property directly as per Leszek's answer, I'd probably use the null-conditional operator in conjunction with the null-coalescing operator:虽然您可以按照 Leszek 的回答直接使用
Value
属性,但我可能会将空条件运算符与空合并运算符结合使用:
string dateInUTCString =
date?.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ", CultureInfo.InvariantCulture)
?? "";
Here the ?.
这里的
?.
will just result in a null value if date
is null, and the ??
如果
date
为空,则只会导致空值,而??
operator will provide a default value if the result of the date?.ToUniversalTime().ToString(...)
call is null (which would only happen if date
is null).如果
date?.ToUniversalTime().ToString(...)
调用的结果为 null(只有在date
为 null 时才会发生date?.ToUniversalTime().ToString(...)
运算符将提供一个默认值。
Note that you really want to specify the invariant culture to avoid getting unexpected results when the current thread's culture doesn't use the Gregorian calendar, and you don't need to quote all those literals in the format string.请注意,您确实希望指定不变区域性以避免在当前线程的区域性不使用公历时获得意外结果,并且您不需要在格式字符串中引用所有这些文字。 It certainly works when you do so, but it's harder to read IMO.
当你这样做时它当然有效,但更难阅读 IMO。
If you don't mind how much precision is expressed in the string, you can make the code simpler using the "O" standard format string :如果您不介意在字符串中表达多少精度,您可以使用“O”标准格式字符串使代码更简单:
string dateInUTCString = date?.ToUniversalTime().ToString("O") ?? "";
At that point you don't need to specify CultureInfo.InvariantCulture
as that's always used by "O".那时您不需要指定
CultureInfo.InvariantCulture
,因为“O”总是使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.