gpt4 book ai didi

c# - 转换日期时间?仅日期然后返回日期时间? (可能的?)

转载 作者:行者123 更新时间:2023-11-30 13:35:38 25 4
gpt4 key购买 nike

我不知道这是否有意义,但我有一个 DateTime?对象,我只想要它的日期部分,但我需要它将它转换回 DateTime?并仅使用日期值存储它。这可能吗?

这是我尝试过的:

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;

关于c# - 转换日期时间?仅日期然后返回日期时间? (可能的?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49545247/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com