Reputation: 167
I have one datetimepicker which custom format MM/dd/yyyy h:mm tt
I have database and has a column "Date_Time" the value of the DateTimePicker is saved to the column Date_Time formatted like this MM/dd/yyyy h:mm tt
now i want to get the Time only not the entire value of datetimepicker just the hh:mm tt from the column Date_Time
SORRY FOR MY GRAMMAR
Upvotes: 1
Views: 4369
Reputation: 38865
You are heading for a new problem. If you zero out the Date portion and store the result to a DateTime
column, you will end up storing something like: 0001-01-01 16:43:12
. A column defined as DateTime
will always have a Date
, as will a DateTime
variable.
The first problem may be getting MySQL
to accept a non-Date in a DateTime
column. Using a column defined as DateTime(3)
, mine throws a generic fatal error exception trying to store just a TimeSpan
to it:
cmd.Parameters.Add("@p3", MySqlDbType.DateTime).Value = DateTime.Now.TimeOfDay
cmd.ExecuteNonQuery()
If MySqlDbType.Time
is used as the type, I get an exception that the time is an invalid value for the column...and it is.
If you manage to store it somehow, the next problem will be when/if you want to put that value back in a DateTimePicker
: the minimum date you can enter is 1/1/1753
(first full year of the current calendar). So your DateTime
var with the Date
zeroed out wont work. You'll first have to restore the date portion, but the Date
, Year
etc are all readonly.
Define the column as Time(0)
which will store hours, minutes and seconds. Use the value in the parens to specify fractional seconds, for instance Time(3)
will also store milliseconds. When you read the data, store it to a TimeSpan
.
Then in your UI use a different control, otherwise you have the same problem - adding some Date data to it to make it usable in a DateTimePicker
Use a DateTimePicker
and a DateTime
column, but just ignore the Date portion in your code. This will allow you to use what is in the Database as is with the control.
You can get the time selected with DateTime.TimeOfDay
but storing and reusing it may be problematic.
Upvotes: 1
Reputation: 2000
The answer above is right.
If you need to get time string, you can use also another way, which includes a formating:
Dim myTimeString = DateTimePicker1.value.ToString("hh:mm")
You can do that for any part of the DateTime value.
Upvotes: 1
Reputation: 18310
How about DateTime.TimeOfDay?
It returns the time that has elapsed since midnight (which is what h:mm tt
stands for in your code).
Dim Time As TimeSpan = DateTimePicker1.Value.TimeOfDay 'Would return for example 3:14 PM
Upvotes: 2