Click here to Skip to main content
Click here to Skip to main content

Time Picker

By , 19 Mar 2011
 

Introduction

My code is very simple. It is a user control that does a very similar thing to the standard DateTimePicker however, it is solely a time picker but, unlike DateTimePicker, it allows the user to set milliseconds, not just hours, minutes and seconds.

Background

I am developing a sound player (of sorts) and found the need to have a time picker that could select hours, minutes, seconds and milliseconds but found that the DateTimePicker couldn't do milliseconds. After asking on the CP Q/A forum if any control existed to do what I wanted, I found the answer came back in the negative. So, here is what I have produced to fill my need and hopefully, that of many other people.

Using the Code

The code is very simple using only a text box in the user control. To use it in your application, simply:

  1. Add the TimePicker control to your project.
  2. Rename the TimePickerDemo namespace in the TimePicker.cs and TimePicker.desginer.cs files to your project's namespace.
  3. Add a TimePicker control to a form.
  4. Use the control's OnValueChanged event and Value member to get the time selected by the user. The Value is stored as a TimeSpan.

The control has several useful members; Hours; Minutes; Seconds; Milliseconds and Value which allow you to get and set the time in the time picker. The Value member is a TimeSpan where the Days part is ignored. The code itself is very simple and so I will only demonstrate a small part of it below. The code handles several events in the following ways:

  • LostFocus - The control has lost the focus so the value in it should be what the user wants so format it to make sure.
  • KeyDown - The user has pressed a key. The accepted keys are numeric keys or arrow keys. Left/right arrow keys switch which part of the time is being edited and the up/down arrow keys increment or decrement the part being edited. Parts are hours, minutes, etc.
  • Click - The user has clicked on a part of the control and so has changed the current part being edited. Update the textbox selection accordingly.
  • TextChanged - This is used only to format the text in the text box when the user types an accepted key.

There isn't much to say about the code in this control, it's simple and fairly boring/trivial and warrants only the explanation given. Therefore below I have placed a sample of the FormatText, SetText and SelectCorrectText methods which are the two key methods in this class.

Format Text and Set Text

string[] Parts = TheTimeBox.Text.Trim().Split(":".ToCharArray());

int Hours = 0;
if (!int.TryParse(Parts[0], out Hours))
{
    Hours = 0;
}
if (Hours >= 24)
{
    Hours = 0;
}

int Minutes = 0;
if (!int.TryParse(Parts[1], out Minutes))
{
    Minutes = 0;
}
if (Minutes >= 60)
{
    Minutes = 0;
}

string[] SecondParts = Parts[2].Split(".".ToCharArray());

int Seconds = 0;
if (!int.TryParse(SecondParts[0], out Seconds))
{
    Seconds = 0;
}
if (Seconds >= 60)
{
    Seconds = 0;
}

int Milliseconds = 0;
if (!int.TryParse(SecondParts[1], out Milliseconds))
{
    Milliseconds = 0;
}
if (Milliseconds >= 1000)
{
    Milliseconds = 0;
}

SetText(Hours.ToString("D2"),Minutes.ToString("D2"), 
	Seconds.ToString("D2"), Milliseconds.ToString("D3"));
if (OnValueChanged != null)
{
    OnValueChanged.Invoke(null, new EventArgs());
}

Set Text

private void SetText(string Hour, string Minute, string Second, string Millisecond)
{
      int SelectedIndex = TheTimeBox.SelectionStart;
      TheTimeBox.Text = Hour + ":" + Minute + ":" + Second + "." + Millisecond;
      SelectedIndex = SelectedIndex > TheTimeBox.Text.Length ? 
			TheTimeBox.Text.Length : SelectedIndex;
      SelectCorrectText(SelectedIndex);
      if (!DoingFormatting)
      {
      	DoingFormatting = true;
         FormatText();
         DoingFormatting = false;
      }
}

Select Correct Text

private void SelectCorrectText(int SelectedIndex)
{
      if (SelectedIndex <= 2)
      {
	 TheTimeBox.Select(0, 2);
      }
      else if (SelectedIndex <= 5)
      {
          TheTimeBox.Select(3, 2);
      }
      else if (SelectedIndex <= 8)
      {
          TheTimeBox.Select(6, 2);
      }
      else
     {
          TheTimeBox.Select(9, 3);
     }
}

History

  • 19th March, 2011: Initial version

License

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

About the Author

Ed Nutting
Founder Slide My Way Limited
United Kingdom United Kingdom
Member
Hi there, so you're reading this? I probably ought to tell you something helpful then...
 
Okay well, I'm 17 from London, UK and I have been programming since I was 8 years old. You'll see from my profile I've dabbled in a lot of different areas and I do know what I'm talking about so as they say "gimme some respect yeah?" Smile | :) I've done GCSE's (got 7A*'s, 2A's and a B in French) and am now studying for my AS-Levels (Math, Further Maths, Physics and Chemistry). My main aim is to go to university to study electronic engineering and then work in robotics (preferably humanoid but most of the field is interesting).
 

I have recently launched my website www.slidemyway.co.uk so please head over and take a look! All support and feedback is welcome!

 
Thanks for reading,
Edward Nutting

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralTimepickermemberRex_kz18 May '11 - 0:06 
Hi! More logical would be to expand the TextBox for this purpose. I rewrite your code, this is a thing what i need. Good snippet =)
GeneralRe: TimepickermemberEdMan19618 May '11 - 7:58 
Agreed that in a general case it would be, but that wasn't quite what I needed at the time Poke tongue | ;-P
QuestionScreendump?memberJohnny J.21 Mar '11 - 22:21 
It would be nice to see what it looks like without having to download anything (that might not be what you want)...
Beidh ceol, caint agus craic againn - Seán Bán Breathnach
-----
Don't tell my folks I'm a computer programmer - They think I'm a piano player in a cat house...
-----
Da mihi sis crustum Etruscum cum omnibus in eo!
-----
Everybody is ignorant, only on different subjects - Will Rogers, 1924

QuestionWhy not inherit?membertlhintoq21 Mar '11 - 13:05 
Why re-invent the wheel from scratch?
Wouldn't it have been more direct to inherit from the DateTimePicker then make a couple changes for milliseconds?
AnswerRe: Why not inherit?memberEdMan19621 Mar '11 - 21:13 
Perhaps but I didn't want to have to meddle in inheriting from DTP. It is only a formatted textbox after all... Poke tongue | ;-P
GeneralCould Use An ImagemvpAspDotNetDev19 Mar '11 - 16:24 
Your article could use an image or two. Maybe a screenshot of your control in action? I am not sure if it looks like the built-in DateTimePicker or if it is more gaudy.

GeneralRe: Could Use An ImagememberEdMan19619 Mar '11 - 23:17 
Yes sorry I will find time to update it then. Just so you know though, the picker is not gaudy at all, it is just a text box. (I thought I said that? Unsure | :~ ) Anyway, so yeah just a text box nothing else. It is identical to the DateTimePicker other than that it doesn't hav the up/down arrow buttons and it only does time (inc. milliseconds). It even has same functionality i.e. up/down keys increment/decrement value, left/right keys change the bit being edited and it highlights the part you are currently editing.
 
Hope this clears it up a bit,
Ed Smile | :)

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 19 Mar 2011
Article Copyright 2011 by Ed Nutting
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid