[英]Convert DateTime? to Date only and then back to DateTime? (Possible?)
我不知道這是否有意義,但我有一個DateTime? 對象,我只想要它的日期部分,但我需要它將它轉換回DateTime? 並使用Date值存儲它。 這可能嗎?
這是我試過的:
public DateTime? StartDate{ get; set; };
DateTime? x = Convert.ToDateTime(StartDate.Value.ToString("MM-dd-yyyy"));
如果我保持
StartDate.Value.ToString("MM-dd-yyyy")
它有效,但我還想要一個DateTime? 對象,因為這是我的數據庫存儲它的方式。 我怎樣才能做到這一點?
你可以這樣做:
DateTime? x = StartDate.HasValue //Handle when value is null
? StartDate.Value.Date //If not null, get date part
: (DateTime?)null; //otherwise just return null
使用null條件運算符的更簡單的版本是:
DateTime? x = StartDate2?.Date;
嘗試這個
DateTime? date = StartDate?.Date;
這真的是你需要寫的。 Date
屬性實際上是DateTime
類型,只是返回從當天頂部開始的實例。 由於您的StartDate
為空,因此使用null條件( ?.
)運算符意味着結果值也可以為空。
這意味着如果它的左側是零,那么它的右側也是如此。 因此結果是DateTime?
的正確類型DateTime?
。
這種方法安全,簡潔,慣用且健壯。
如果您需要如何格式化以僅顯示日期組件,我也包括它。
DateTime? onlyDate = oldData?.Date;
if (onlyDate.HasValue)
{
string formattedDate = onlyDate.Value.ToString("dd/MM/yyyy"));
//or dd-MM-yyyy
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.