Limit hour DateTimePicker to 30 minute intervals [duplicate] - c#

This question already has answers here:
How to contol the time interval in a DateTimePicker
(6 answers)
Closed 8 years ago.
I have several DateTimePicker controls in C# and I need to limit the user to only choose from 30 minute intervals, e.g. 9:00 --> 9:30 --> 10:00 --> 10:30, and so on. Is this possible?

public Form1()
{
InitializeComponent();
if (dt.Minute % 30 > 15)
{
initialValue = true;
dateTimePicker1.Value = dt.AddMinutes(dt.Minute % 30);
}
else
{
initialValue = true;
dateTimePicker1.Value = dt.AddMinutes(-(dt.Minute % 30));
}
_prevDate = dateTimePicker1.Value;
}
private DateTime _prevDate;
private bool initialValue = false;
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
if(initialValue)
{
initialValue = false;
return;
}
DateTime dt = dateTimePicker1.Value;
TimeSpan diff = dt - _prevDate;
if (diff.Ticks < 0)
dateTimePicker1.Value = _prevDate.AddMinutes(-30);
else
dateTimePicker1.Value = _prevDate.AddMinutes(30);
_prevDate = dateTimePicker1.Value;
}
This should work. You need global variable/Property to store _prevDate. You set the _prevDate in Form1() or on Form Load.
How we are adding/removing 30 minutes every time.
On value Change event you are taking the current dataPicker Value, after that you calculate the difference between currentValue and prevValue. If the value > 0 Add, and value<0 Remove.
If you don't know how to change the DatePicker to show minutes you need this to add in the designer.
You need this code:
this.dateTimePicker2.CustomFormat = "dd/MM/yyyy hh:mm";
this.dateTimePicker2.Format = System.Windows.Forms.DateTimePickerFormat.Custom;
this.dateTimePicker2.ShowUpDown = true;
EDIT:
I add the code which will start the DataPicker on 00 or 30 depending how close is to 30 or 00. You need another global variable of type bool which will put initialValue of the dateTimePicker. See the code.

Related

How to validate if the input time is within the given time range in asp.net C#?

My time range is 08:00 AM to 03:00 PM.
If the selected input time does not exist within this range it should throw an error message.
How to do this?
Can anybody help me out?
protected void txtTimeIn_TextChanged(object sender, EventArgs e)
{
DateTime time = Convert.ToDateTime(txtTimeIn.Text);
TimeSpan start = new TimeSpan(8, 0, 0);
TimeSpan end = new TimeSpan(15, 0, 0);
TimeSpan now = new TimeSpan(time.Ticks);
if ((now > start) && (now < end))
{
lblIN.Visible = false;
}
else
{
lblIN.Visible = true;
}
}
When i select the wrong time the label is displayed, but once i change and select the correct time the label is not disappearing.
public void Page_Load(object sender, EventArgs e)
{
TimeSpan startTime = new TimeSpan(8, 0, 0); // 8 AM
TimeSpan endTime = new TimeSpan(15, 0, 0); // 3 PM
if (DateTime.Now.TimeOfDay > startTime && DateTime.Now.TimeOfDay < endTime)
{
// Execute logic
}
}
Here is a quick and easy solution to check against the current DateTime. Obviously you said you have a "selected date" but I don't see that anywher, so just convert that to a DateTime if needed.

How to get Timespan in Milliseconds

I want to get the timespan in milliseconds by comparing two timestamps with DateTime.Now and the previous DateTime. I want to check if there is an event every 10 Milliseconds or later but the totalmilliseconds from DeltaT is like 188 or so. It is too high than I am expecting that is why I think there must be somethimg wrong. Or does everything look alright?
DateTime timestamp;
DateTime timestampAlt;
TimeSpan deltaT;
public void OnSensorChanged(SensorEvent e)
{
timestamp = System.DateTime.Now;
deltaT = timestamp - timestampAlt;
if (deltaT.TotalSeconds <= 0.01)
{
return;
}
UPDATE:
I really appreciate all of you answers but I think there is a misunderstanding (my mistake sry). So here again:
Whenever the listener recognizes an event, I want to save the timestamp and compare with the timespamp of the event before. If there is a gap of more than 10 Milliseconds between the 2 events, then I do want to know more about this new event. If not, I dont even want to continue and will leave by a return.
public void OnSensorChanged(SensorEvent e)
{
timestamp = System.DateTime.Now;
deltaT = timestamp - timestampAlt;
//int deltaT2 = timestamp.Millisecond - timestampAlt.Millisecond;
String timestampStr = timestamp.ToString("ff");
String timestampStrA = timestampAlt.ToString("ff");
if (deltaT.TotalMilliseconds <= 10 || deltaT.TotalMilliseconds <= -10) //deltaT.Seconds <= 0.01
{
return;
}
timestampAlt = timestamp;
newValue = e.Values[2];
//if (buffer[99] != 0.00)
// if last element of list is empty, add elements to buffer
if (buffer.Count <=99)
{
buffer.Add(newValue);
zeitbuffer.Add(timestamp);
}
else
{
Ableitung(DeltaBuffer(), DeltaTime()); // if last index of list is filled, do that function
}
if (e.Values[2] >= 11)
{
try
{
lock (_syncLock)
{
String z2 = newValue.ToString("0.0");
//noteInt2 = Convert.ToInt32(newValue);
try
{
_sensorTextView2.Text = string.Format("Note: {0}", z2 );
eventcounter.Add(z2);
You can use deltaT.TotalMilliseconds which expresses your delta in milliseconds. Therefore your check could be rewritten as
if (deltaT.TotalMilliseconds <= 10)
{
return;
}
10 is a value I inferred. It might not be what you need, but your question is partial. This answer addresses your particular question, however if you need to measure the duration of a task you should use the Stopwatch class, which is designed for that purpose.
if you want to fire an event every n-Seconds you can use a timer that fires an event when he elapses:
Timer timer = new Timer();
timer.Interval = 100;
timer.Elapsed += YourAmasingEvent;
timer.Start();
private void YourAmasingEvent(object sender, ElapsedEventArgs e)
{
//do something here
(sender as Timer).Start();
}
Using your code:
I guess you want to wait until the time elapsed in this case you would have to use a loop like this:
timestamp = System.DateTime.Now;
deltaT = timestamp - timestampAlt;
while(true)
{
if (deltaT.TotalSeconds <= 0.01)
{
return;
}
timestamp = System.DateTime.Now;
deltaT = timestamp - timestampAlt;
}

Comparing two dates one from the database and datetime.now

I have a gridview and I would like to highlight the days which has difference > 10.
What I have now
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DateTime dateNow = DateTime.Now;
string dateCreated = e.Row.Cells[5].Text;
DateTime dc = Convert.ToDateTime(dateCreated);
TimeSpan difference = dateNow - dc;
if (difference.TotalDays > 0)
{
e.Row.BackColor = System.Drawing.Color.Cyan; // This will make row back color red
}
}
}
Date format of the one saved onto my database is dd-MM-YYYY and it is saved as nvarchar.
Use this:
int minutes = (int)DateTime.Now.Subtract(dc).TotalMinutes;
or days
int days = (int)DateTime.Now.Subtract(dc).TotalDays;
Or seconds, miliSeconds, Weeks, ....
To get date from your string do this:
string dateCreated = "01-01-2017";
string[] dcArray = dateCreated.Split('-');
DateTime dc = new DateTime(int.Parse(dcArray[2]), int.Parse(dcArray[1]), int.Parse(dcArray[0]));
You should parse DateTime like that:
DateTime dc = DateTime.ParseExact(dateCreated, "dd-MM-yyyy", CultureInfo.InvariantCulture);
Victor Leontyev is right on with the parsing. But then you also have to tweak you logic:
if (difference.TotalDays > 0)
to
if (Math.Abs(difference.TotalDays) > 10)

How to create an advanced countdown timer

Well, this question is related to this one, so you guys can understand it better
How to convert the "time" from DateTime into int?
My Answer to it:
txtAtiv.Text = dataGridView1.Rows[0].Cells[1].Value + "";
string value = dataGridView1.Rows[0].Cells[2].Value + "";
lblLeft.Text = value.Split(' ')[1];
textStatus.Text = "";
DateTime timeConvert;
DateTime.TryParse(value, out timeConvert);
double time;
time = timeConvert.TimeOfDay.TotalMilliseconds;
var timeSpan = TimeSpan.FromMilliseconds(time);
lblSoma.Text = timeSpan.ToString();
timer2.Start();
According to the answer I wrote right there, I want to know if there's a way I can apply it to a timer and do the DataGrid values (converted) turn into a timer value. So if I press a button they start the countdown.
I have tried to insert this code inside the timer:
private void timer2_Tick(object sender, EventArgs e)
{
string timeOp = dataGridView1.Rows[0].Cells[2].Value + "";
DateTime timeConvert;
DateTime dateTime = DateTime.Now;
DateTime.TryParse(timeOp, out timeConvert);
double time;
time = timeConvert.TimeOfDay.TotalMilliseconds;
var timeSpan = TimeSpan.FromMilliseconds(time);
if (time > 0)
{
time = time - 1000; //(millisec)
lblCountdown.text = time.ToString();
}
}
didn't count down or anything, does someone has an idea of what should I do or why it isn't working?
The value of time never changes, because you create it again fresh each time.
To solve this, you have to declare the variable you decrement outside of the Tick event.
Put these two variables on your form:
private int milliSecondsLeft = 0;
private bool timeSet = false;
Then change the 'tick' event to this:
private void timer2_Tick(object sender, EventArgs e)
{
if (!timeSet) // only get the value once
{
string dateTimeFromGrid = "4/29/2016 5:00:00 AM"; //hardcoded for simplicity, get the string from your grid
DateTime fromGrid;
DateTime.TryParse(dateTimeFromGrid, out fromGrid);
milliSecondsLeft = (int)fromGrid.TimeOfDay.TotalMilliseconds;
timeSet = true;
}
milliSecondsLeft = milliSecondsLeft - 100; // timer's default Interval is 100 milliseconds
if (milliSecondsLeft > 0)
{
var span = new TimeSpan(0, 0, 0, 0, milliSecondsLeft);
lblCountdown.Text = span.ToString(#"hh\:mm\:ss");
}
else
{
timer2.Stop();
}
}
Make sure

Windows Phone countdown app

I am trying to do two things:
On Christmas day, invoke a method whenever the page is navigated to.
After Christmas day, set the christmasDay DateTime to +1 year (so the countdown "resets").
Here is my code:
private void OnTick(object sender, EventArgs e)
{
DateTime christmasDay;
DateTime.TryParse("11/17/13", out christmasDay);
var timeLeft = christmasDay - DateTime.Now;
int x = DateTime.Now.Year - christmasDay.Year;
if (DateTime.Now > christmasDay)
{
if (x == 0)
x += 1;
christmasDay.AddYears(x);
if (DateTime.Now.Month == christmasDay.Month && DateTime.Now.Day == christmasDay.Day)
{
itsChristmas();
}
}
countdownText.Text = String.Format("{0:D2} : {1:D2} : {2:D2} : {3:D2}", timeLeft.Days, timeLeft.Hours, timeLeft.Minutes, timeLeft.Seconds);
}
When I set the date to TODAY, the "itsChristmas()" method works...but I don't actually want it to be invoked on each tick of the countdown. I tried putting it in the constructor of the page but that doesn't work. Any ideas?
The second problem is that if I set the date to a day before today, it gives me negative numbers. I don't know what is wrong with my code that this is happening. :(
Your solution is quite complex. You could solve it like this.
private void OnTick(object sender, EventArgs e)
{
var now = DateTime.Now;
var christmasDay = NextChristmas();
if (now.Date < christmasDay.Date)
{
// it's not christmas yet, nothing happens
}
if (now.Date == christmasDay.Date)
{
// it's christmas, do your thing
itsChristmas();
}
}
private DateTime NextChristmas()
{
var thisYearsChristmas = new DateTime(DateTime.Now.Year, 12, 25);
if (DateTime.Now.Date <= thisYearsChristmas.Date) return thisYearsChristmas;
return thisYearsChristmas.AddYears(1);
}
The if statemements can be written more consise but I elaborated on them to make clear what happens.

Categories

Resources