简体   繁体   中英

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?

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

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
}

尝试这个。

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

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