简体   繁体   中英

Change format of DateTime without converting to string

I'm new in c# and I have Datetime variable like:

DateTime startingDate

value = 8/8/2018 4:16:18 PM

I want value like 8/8/2018 , how can I just drop hours minutes seconds and PM value without converting to string? because I'm forced DateTime type for another thing.

In C# (as in many other languages) there is no separate Date and Time , it's just DateTime . Regardless of that though, there are many use cases where you only need a date. In C# it's assumed that if you just need 8/8/2018 then in reality you are working with 8/8/2018 0:00:00.000 .

If you need to work with just the Date but still keep it as a DateTime, then the most straightfoward method is to use .Date (ie startingDate.Date ). This can get a little confusing since the default .ToString() for DateTime represents it (in whatever is the cultural norm for your computer) as Month/Day/Year Hour:Minute:Second AM/PM.

Also, for further clarification, DateTime is an object that has a variety of different properties ( Year, Month, Day, Hour, Minute, Second etc), so thinking of it having a "format" is incorrect. It's a collection of things that together make up a Date and/or Time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM