c# - 无法从日期类型中提取日期部分
问题描述
我在我的 c# 代码中将字符串转换为日期,现在我列中的所有值都是日期类型。我只想在列中显示日期,但仍然看到日期 + 小时,例如现在显示 20.10.2020 00:00:00 而我只想要 20.10.2020。
我尝试仅提取日期部分,但它不起作用。我必须返回日期类型 btw,而不是字符串。我的尝试如下所示(此代码有效 - 转换为日期但不是所需的格式,我的意思是只有日期部分):
public DateTime? ConvertDate(decimal? date)
{
if (date == null)
{
return null;
}
else
{
string dateString = date.ToString();
string year = dateString.Substring(0, 4);
string month = dateString.Substring(4, 2);
string day = dateString.Substring(6, 2);
int yearInt;
int monthInt;
int dayInt;
bool successYear = Int32.TryParse(year, out yearInt);
bool successMonth = Int32.TryParse(month, out monthInt);
bool successDay = Int32.TryParse(day, out dayInt);
DateTime convertedDate = new DateTime(yearInt, monthInt, dayInt);
//string shortDateTime = convertedDate.ToString("d"); i tried this but no difference in showing date
//DateTime shortDate = Convert.ToDateTime(shortDateTime); i also tried this but no difference in showing date
return convertedDate;
}
}
解决方案
相反,您应该使用日期格式。
string DateToDateString(DateTime date)
{
return string.Format("{0:dd/MM/yyyy}", date);
//dd day,
//MM month
//yyyy year
//If you need,
//HH for hour (24h)
//hh for hour (12h)
//mm for minute
}
推荐阅读
- node.js - 无法使用解构导入类的静态方法
- scala - 如何在 Scala 中从 Future[Either[Left, Right]] 获取 Future[Right]?
- python - 我正在尝试制作网络抓取工具,但我不断收到此错误
- javascript - 动画儿童旋转面对相机没有给出预期的结果三个js
- image-segmentation - Maskrcnn:误报
- html - CSS `z-index`:使列表项出现在 *previous* 项下方
- python - 使用队列的 Python 程序
- java - 如何在 Kotlin 中获取当前工作目录?
- python - 使用 Open CV 去除背景不精确,部分图片无法正确完成
- arrays - 下拉菜单未反映在 UI 中