C# convert string to datetime without time

2019-09-18 14:53发布

问题:

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

回答1:

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.



回答2:

myDatTime.ToString("MMM dd, yyyy"); would do the trick



回答3:

If I understand you .. this may help.
in c#:
if(!string.IsNullOrEmpty(yourDateTime)) { yourDateTime.ToString("dd/MM/yyyy"); }
in sql-server:

select convert(varchar, yourDateTime ,102) as [yourDateTime]