views:

524

answers:

2

hi..i want to know the way to extract date and time separately from the currently selected value in datetime picker control??

+1  A: 

DateTimePicker.Value returns a DateTime, so you can use the Date and TimeOfDay properties of DateTime.

Important Note:

If you're saving the value to a database, put the date value in a data parameter, don't concatenate strings to build SQL queries; that'll leave you open to the SQL injection attack. Here's a brief example (not tested code, just to give you an idea):

DateTime theDate = dtPicker.Value.Date;
IDbCommand command = GetDbCommand("insert into table_name (name, thedate) values (@name, @thedate)");
command.Parameters.Add(command.CreateParameter("@name", theName));
command.Parameters.Add(command.CreateParameter("@thedate", theDate));
command.ExecuteNonQuery();

More info on avoiding SQL injection attacks (and solving your "invalid month") problem can be found here:

http://blogs.msdn.com/raulga/archive/2007/01/04/dynamic-sql-sql-injection.aspx

Neil Barnwell
Might be that it's trying to store the day and month the wrong way round (US format dates are 1/31/2009, UK ones are 31/1/2009, for example). Check regional settings and current culture information.
Neil Barnwell
Whoa, hang on. You shouldn't be using the string value in a SQL statement - that'll leave you open to SQL Injection attacks. Use SQL data parameters instead.
Neil Barnwell
A: 

if you just want them for display purposes, you can to the following:

DateTimePicker.Value.ToShortDateString() - will give you a date string
DateTimePicker.Value.ToShortTimeSttring() - will give you time string

roman m
i dont want it for only display purposes..i have to store these values in the oracle database..please help
store them in what format? if it's a varchar field - my method will work just fine for you
roman m
date is to be stored in date type field and time in char type..
i'm not too familiar with oracle, but looks like you should use DateTimePicker.Value.Date for your Date column, and DateTimePicker.Value.ToShortTimeSttring() for your time column
roman m
Don't store dates in varchar fields - that way lies madness. There are datetime datatypes in databases for a reason - use them.
Neil Barnwell