首页 > 解决方案 > 无法从日期类型中提取日期部分

问题描述

我在我的 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;



            }
        }

标签: c#

解决方案


相反,您应该使用日期格式。

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

}

推荐阅读