How can I save string value to sql server db datatype as time(7)

236 views Asked by At

I have to save a time to sqlserver2008 db as time(7) data type which is in string format in code behind.how can I convert it to that data type.My code getting error

string time='9.30 pm';
modal db=new modal();
db.time=Timespan.Parse(time);
context.modal.Add(db);
context.SaveChanges();

in db,time as time(7) datatype

error is

An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code. Additional information: String was not recognized as a valid TimeSpan.

1

There are 1 answers

0
Zohar Peled On

Based on this answer, you can do this:

string time="9.30 pm";
TimeSpan ts = DateTime.ParseExact(time, "h.mm tt", CultureInfo.InvariantCulture).TimeOfDay;

db.time = Timespan.Parse(ts);
context.modal.Add(db);
context.SaveChanges();