如何在 C# 中将 DateTime 转换为 int?

How can I convert a DateTime to an int in c#?

我正在使用 Asp.Net 并希望将日期时间转换为整数格式。我从 SQL.

得到这个日期
> I want 2021/03/15 date into 1210315 in my application and will use it further.
> 
> Here, 1 is century, 21 is year, 03 is month, and 15 is date.

我在谷歌上搜索了很多,但找不到任何解决方案。 如果有人有任何想法,请提供解决方案,我们将不胜感激.....谢谢

我简单描述一下我的问题:

这是我的存储过程

create proc spMaxDate
As
Begin
select max(Date) from Customer
End

然后在我的应用程序中,我从这个存储过程中获取了最大日期:

var SQlDate = db.spMaxDate().FirstOrDefault();

在这里,我得到的日期是 2021/03/15。 所以,我必须按照前面所述将其转换为 1210315 格式......或者如果可以将其转换为 SQL select 语句,那么你可以告诉。

我能想到的处理这个奇怪要求的最明智的方法

DateTime date = DateTime.Now; //Populate this from your db

int iDate = int.Parse(date.ToString("yyyyMMdd")) - 19000000;

Demo

在数据库中你可以使用:

select (year(datecol) - 1900) * 10000 + month(datecol) * 100 + day(datecol)

大多数数据库都支持这些功能。在某些情况下,您需要改用 extract()