I'm trying to create a string from the DateTime object which yields the format mm:dd:yyyy
.
Conventionally the DateTime
object comes as mm:dd:yyyy hrs:min:sec AM/PM
.
Is there a way to quickly remove the hrs:min:sec AM/PM
portion of the DateTime so that when I convert it ToString()
it will only result in mm:dd:yyyy
?
A faster way would be to work with the Ticks property: DateTime dtNew = dt. AddTicks(-(dt. Ticks % 10000000));
Using strfttime to Remove the Time from Datetime in Python We can use strftime() to easily remove the time from datetime variables. For example, if you want to print out the date in the format “YYYY-MM-DD”, we pass “%Y-%m-%d” to strfttime() and no time is printed.
Solution 1 Using different methods on the DateTime, like . Today give the date part, but the other parts of it are zero. This is by design. If you don't want to display the seconds when you create the string, use a format string, like MM/dd/yyyy hh.mm and leave the tt part off.
To answer your question, no - you would have to store it in a different type. The most simple choice is to use a string.
string date = dateTime.ToString("MM:dd:yyyy");
However I'd also strongly advise against storing dates internally in your program as strings. This will make it difficult to do any calculations or comparisons on them. Furthermore I'd advise you against forcing a specific culture for your date representation as it means your application probably won't work as expected in other cultures than yours.
A slightly more sophisticated approach is to create a custom class which overrides ToString. I'd also avoid this though, because it will still be difficult to use your type with the standard library functions. You will have to convert back and forth all the time.
Just leave it as a DateTime and do the conversion to string only in the presentation layer. You can use DateTime.ToShortDateString
to print a user friendly culture aware string.
While in most cases I agree with Mark Byers, I had a situation where I needed to store a date time that was only ever granular to the hour. Storing minutes and seconds would not only be superfluous, but also inaccurate. The user simply selected a date and hour, so while the date and hour would be user selected, the minutes and seconds would be set to whatever the current time was.
Removing minutes and seconds is very easy in this case. Here is the code:
scheduledDate = scheduledDate.AddMinutes(
scheduledDate.Minute * -1).AddSeconds(
scheduledDate.Second * -1);
Then I store it in the DB as a full date time, with minutes and seconds always 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With