C#将字符串转换为没有时间的日期时间 [英] C# convert string to datetime without time
问题描述
DateTime
。在数据库中,它被写为01.01.2011,但是当我用SQL读取并将它存储在字符串
中时,它会显示01.01.2011 00:00:00 。 然后,我认为确定,我会从
字符串
中减少时间。但有一个窍门,看来这是不可能的。即使当我从字符串
(它只是说01.01.2011)中删除00:00:00部分,并将其转换为 DateTime
,仍然显示00:00:00。 我是C#的新手,但是看起来这个部分在Java中可以更好的解决,你可以定义你想要怎样的日期,并且可以像这样显示(不需要连续的时间)。
所以为了说清楚,是否真的不可能实现我想要的(而且我必须处理我的表示层中正确的格式),还是我没有找到正确的信息呢?
谢谢
DateTime
跟踪自1/1/0001以来的所有刻度。 (毫秒中有一万个刻度)。所以 DateTime
不是 是不可能有时间组件的。对于仅限日期的数据,常规惯例是使用时间设置为午夜(00:00:00)的日期。您可以通过使用 .Date
属性从任何 DateTime
获取其中的一个。
你一定要小心,一旦你忽略了时间,你总是忽略时间。否则,在巴西等地处理日光节约时间问题时,可能会遇到问题 - 时间从下午11:59:59到凌晨1:00:00。如果你不太在意你如何处理你的数据,那么在午夜填入 DateTime
的只有日期的数据可能会被误解为本地时间,而实际上并不存在。
在.NET Framework中没有一个真正的日期没有内置的类型。但是,您可以在 LocalDate $ c Noda Time 库的结构。如果您有很多基于日期的业务逻辑,您可以考虑使用它。
It seems like it is not possible what I want(at least according to some articles i have read). But just to double check it. I am reading a DateTime
from my database. In the database it is written like "01.01.2011" but when I read it with SQL and store it in a string
it says "01.01.2011 00:00:00".
Then I thought OK, I will just cut the time from the string
. But there is the trick, it seems like this is not possible. Even when I cut the "00:00:00" part from the string
(and it just says "01.01.2011"), and covert it into a DateTime
, the "00:00:00" is still being displayed.
I am new to C#, but it seems like this part is a lot better solved in Java where you can define how you want your date and it is being displayed like that (without concatting time when you don't want it).
So just to make it clear, is it really not possible to achieve what I want (and I have to take care of the right format in my presentation layer) or did I just not find the proper information?
Thanks
DateTime
in .Net is always a date and a time. You can ignore the time portion if you like, but it is still there. Internally, DateTime
tracks the whole number of ticks since 1/1/0001. (There are 10,000 ticks in a millisecond). So it is not possible for a DateTime
to not have a time component.
For date-only data, the common convention is to use a date with the time set to midnight (00:00:00). You can get one of these from any DateTime
by using its .Date
property.
You'll want to be careful that once you ignore the time, that you always ignore the time. Otherwise, you may get into problems when dealing with daylight saving time issues in places like Brazil - where the time transitions from 11:59:59 PM to 1:00:00 AM. If you're not careful about how you handle your data, then date-only data stuffed in a DateTime
at midnight could get misinterpreted as a local time that doesn't actually exist.
There is no built-in type for a true date without a time in the .NET Framework. However, you can find it in the LocalDate
structure of the Noda Time library. You might consider using that if you have a lot of date-based business logic.
这篇关于C#将字符串转换为没有时间的日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!