azalikaEriya
azalikaEriya

Reputation: 195

C# Convert String to DateTime (AM : PM)

There is a textbox in my application which is used to input time (Hour and Minute) with AM PM. In the database the relevant field for that textbox is "Times" which hold the datatype as DateTime

string times = "06:45 AM";

To DateTime for Sql-Server (YYYY-MM-DD HH:mm:ss)

How do I convert input form textbox to database?

Upvotes: 4

Views: 3683

Answers (3)

SAR
SAR

Reputation: 1845

Try this.

   TimeSpan theTime = DateTime.Parse("06:45 AM").TimeOfDay;

Upvotes: 0

Soner Gönül
Soner Gönül

Reputation: 98750

Sql Server's datetime type always have date and time part.

If you wanna insert this hour part with Today's date, you can directly parse this string to Datetime and you can insert this DateTime to your database. Like;

string times = "06:45 AM";
DateTime dt;
if(DateTime.TryParseExact(times, "HH:mm tt", CultureInfo.InvariantCulture,
                          DateTimeStyles.None, out dt))
{
    //dt will be 15/01/2015 06:45:00 and insert this DateTime directly
}

Upvotes: 2

Rufus L
Rufus L

Reputation: 37020

var date = DateTime.Parse("06:45 AM");
Console.WriteLine(date);

Upvotes: 4

Related Questions