Limit DateTimePicker to 30 minute intervals C#

I am creating an AddIn for Outlook and I want to create DateTimePicker where I want to select a Time in interval of 30 minutes. In KeyDown event where  the user presses up or down it will increment or decrement the time in interval of 30 minutes.


public partial class DWScheduler : Form
{
// Global variables
private DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 8, 0, 0);
private DateTime _prevDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 8, 0, 0);
private bool initialValue = false;

public DWScheduler()
{
InitializeComponent();

dateTimePicker1.DropDown += new EventHandler(DateTimePicker1_DropDown);
dateTimePickerTime.ValueChanged += new EventHandler(dateTimePickerTime_ValueChanged);

// Define a date time variable
if (dt.Minute % 30 > 15)
{
initialValue = true;
dateTimePickerTime.Value = dt.AddMinutes(dt.Minute % 30);
}
else
{
initialValue = true;
dateTimePickerTime.Value = dt.AddMinutes(-(dt.Minute % 30));
}

_prevDate = dateTimePickerTime.Value;
}
private void dateTimePickerTime_ValueChanged(object sender, EventArgs e)
{
if (initialValue)
{
initialValue = false;
return;
}

DateTime dt = dateTimePickerTime.Value;
TimeSpan diff = dt - _prevDate;

if (diff.Ticks < 0)
dateTimePickerTime.Value = _prevDate.AddMinutes(-30);
else
dateTimePickerTime.Value = _prevDate.AddMinutes(30);

_prevDate = dateTimePickerTime.Value;
}

private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{

}
private void DateTimePicker1_DropDown(object sender, System.EventArgs e)
{
// Load data from calendar

}

private void DWScheduler_Load(object sender, EventArgs e)
{
// set the Date picker to today's date
dateTimePicker1.Value = DateTime.Today;
dateTimePicker1.MinDate = DateTime.Today;

// set the default time
//int hour = 8;
// int minute = 0;
dateTimePickerTime.Value = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 8, 0, 0);

}
}

 

 

, ,

No comments yet.

Leave a Reply

*