Click here to Skip to main content
15,906,708 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
C#
timePicker = new DateTimePicker();
timePicker.Format = DateTimePickerFormat.Time;
timePicker.ShowUpDown = true;
timePicker.Location = new Point(10, 10);
timePicker.Width = 100;
Controls.Add(timePicker);


i want to store time into database (time selected by user)....

i m using this code
C#
DateTime d=DateTime.Now;
TimeSpan ts = d.Subtract(timePicker.Value);

this code is not working
Posted
Updated 27-May-14 21:11pm
v2

What is not working? This is the correct way of getting time span, only using the operator '-' (subtraction) defined for DateTime would be much better, because it makes the operation and sign of the result more obvious.

If you need time span, this is what you should do. If you want to get something else, do something else. :-)

—SA
 
Share this answer
 
You have to subscribe to the valuechanged event to do what you like

C#
private void Form1_Load(object sender, EventArgs e)
        {
            var timePicker = new DateTimePicker();
            timePicker.Format = DateTimePickerFormat.Time;
            timePicker.ShowUpDown = true;
            timePicker.Location = new Point(10, 10);
            timePicker.Width = 100;
            timePicker.ValueChanged += timePicker_ValueChanged;
            Controls.Add(timePicker);
        }

        void timePicker_ValueChanged(object sender, EventArgs e)
        {
            var picker = (DateTimePicker) sender;
            if (picker == null) return;

            DateTime d = DateTime.Now;
            var ts = d.Subtract(picker.Value);
            System.Diagnostics.Debug.WriteLine("We get a total of {0} seconds", (int) ts.TotalSeconds);
         }
 
Share this answer
 
Try like this
C#
TimeSpan ts = d.Subtract(Convert.ToDateTime(timePicker.Value.ToShortTimeString()));

where timePicker.Value.ToShortTimeString() gives the time picked by the user ( Format will be (HH:MM AM/PM)
 
Share this answer
 
v2
you can use
C#
TimeSpan ts =timePicker.Value.TimeOfDay


DateTimePicker.Value Property[^] gives you a DateTime value. to get the time of day you can use DateTime.TimeOfDay Property[^], no need to any casting :-)
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900