Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to specific DateTime format

Tags:

c#

asp.net

I've been googling for a while now and for the life of me can't seem to find a solution. I thought this would be easy but it's taking too long and am turning to stackoverflow.

I need to convert a string which contains a date and time to a DateTime variable. I've formatted the string in the exact format I want to store it in but when i convert it to a DateTime it keeps adding the seconds which I don't want. I want it stored as 01/01/2010 09:00AM. Here's the code I've been using so far:

DateTime.ParseExact(startTime,"MM/dd/yyyy hh:mmtt", null);

..but it keeps appending seconds to it. Please advise.

like image 523
Joey Avatar asked Jun 04 '26 17:06

Joey


1 Answers

If it's stored as a DateTime data type, it's stored correctly, but your UI is displaying it wrong. The DateTime data type always has the seconds (milliseconds, etc) regardless of how you set the value. The problem is in how it's being displayed back to the user.

You need to display the date you want in the right string format at display time as in

Label1.Text = startTime.ToString("MM/dd/yyyy hh:mmtt");

Edit - added

To format it in a GridView, see here: http://peterkellner.net/2006/05/24/how-to-set-a-date-format-in-gridview-using-aspnet-20using-htmlencode-property/

like image 197
David Avatar answered Jun 06 '26 08:06

David