I have dateTimePicker1 and dateTimePicker2 controls loading on Form1. They both have the same date and time on load.
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "yyyy-MM-dd hh:mm:ss";
dateTimePicker2.Format = DateTimePickerFormat.Custom;
dateTimePicker2.CustomFormat = "yyyy-MM-dd hh:mm:ss"
When I check if they have different values using
if (dateTimePicker1.Value < dateTimePicker2.Value) {
Console.WriteLine(dateTimePicker1.Value + " is earlier than " + dateTimePicker2.Value);
}
the statement returns true and writes to the console. This is not what I would expect. I would expect this to return false.
If I increase each control's value by 1 second, causing them to still match, the statement returns false as expected and nothing is written to the console.
Why does the less than evaluation return true on load when both values are identical?
Do not know how you are loading the values. But, depending on what precision you are looking for (eg. in hours, minutes or second) you can subtract the two values and compare. Example: If you need precision in seconds then you can do something similar to below:
dateTimePicker1.Value = DateTime.Now;
dateTimePicker2.Value = DateTime.Now.AddMilliseconds(999);
var timeSpan1 = dateTimePicker1.Value - dateTimePicker2.Value;
if (Math.Abs(timeSpan1.TotalSeconds) > 1) {
MessageBox.Show(dateTimePicker1.Value + " is not same as " + dateTimePicker2.Value);
} else {
MessageBox.Show(dateTimePicker1.Value + " is same as " + dateTimePicker2.Value);
}
The answer is given by setting the two values equal to each other on load. This is because the controls load at different times. They are not really equal.
private void Form1_Load(object sender, EventArgs e)
{
dateTimePicker2.Value = dateTimePicker1.Value;
}
I'm not sure how to give credit here, it belongs to two commenters.
Related
Why can't I get this audio file played when the time in textboxordertostart.Text in string format equals the system time? Textboxordertostart gets time after subtracting minutes from DateTimePicker time.
My code is as follow.
SoundPlayer myplayer = new SoundPlayer();
myplayer.SoundLocation= (#"c:\users\woolsvalley\documents\visual studio 2015\Projects\WindowsFormsApplication17\WindowsFormsApplication17\Alarm.wav");
if (DateTime.Now.ToString("hh:mm tt") == textBox_ordertostart.Text)
{
myplayer.Play();
}
This code throws a null exception
string formatString = "yyyHHmmss";
string sample = textBox_ordertostart.Text;
DateTime dt = DateTime.ParseExact(sample, formatString, null);
if (DateTime.Now == dt)
{ myplayer.Play(); }
this is not working as well
if (DateTime.Now == DateTime.Parse(textBox_ordertostart.Text))
{ myplayer.Play(); }
The way you're doing the comparison is a very "brittle" way of doing the comparison because it's dependent on the user typing the time in the exact format you're expecting it in. For example, when I tested this, I got the following results:
string datetime = DateTime.Now.ToString("hh:mm tt");
// False
Console.WriteLine(datetime == "2:06 PM");
// False
Console.WriteLine(datetime == "2:06 P.M.");
// False
Console.WriteLine(datetime == "2:06");
// False
Console.WriteLine(datetime == "02:06 P.M.");
// True
Console.WriteLine(datetime == "02:06 PM");
If you parse it to a DateTime object and then do ToString, it'll be less brittle though. See this extension method, for example:
public static bool DayMinuteEqual(this string otherDate)
{
// We have to strip out the "." character if present (e.g. 2:05 P.M.)
DateTime otherDateObj = DateTime.Parse(otherDate.Replace(".", ""));
return DateTime.Now.ToString("hh:mm tt") == otherDateObj.ToString("hh:mm tt");
}
Now I get the results I expect:
// True
Console.WriteLine("2:20 PM".DayMinuteEqual());
// True
Console.WriteLine("2:20 P.M.".DayMinuteEqual());
// False, but we'd expect it due to the omission of the "P.M."
Console.WriteLine("2:20".DayMinuteEqual());
// True
Console.WriteLine("02:20 P.M.".DayMinuteEqual());
// True
Console.WriteLine("02:20 PM".DayMinuteEqual());
Clearly, then, this much less dependent on the user entering the date in a "perfect" format (but still requires them to have some sense of the correct format).
thanks guys. This code works i just needed to raise it in the updating event.
private void timer1_Tick(object sender, EventArgs e)
{ label_time1.Text = DateTime.Now.ToString("hh:mm tt");
mplayer = new SoundPlayer();
mplayer.SoundLocation = (#"c:\users\woolsvalley\documents\visual studio 2015\Projects\WindowsFormsApplication17\WindowsFormsApplication17\Alarm.wav");
if((DateTime.Now.ToString("HH:mm tt") == ((textBox_ordertostart.Text))))
{ mplayer.Play(); }
I'm making a alarm clock in my application and the code requires me to set a variable int from a combo box into my program.
if ((e.Result.Text == "set a alarm") || (e.Result.Text == "set an alarm"))
{
Jarvis.Speak("setting alarm");
label2.Content = DateTime.Today.Hour.ToString(HourAlarmCB) + ":" + DateTime.Today.Minute.ToString("54") + ":" + DateTime.Today.Second.ToString("00");
label2.Opacity = 100;
dispatcherTimer2.Start();
}
The HourAlarmCB is the ComboBox with content in it "1","2", etc. but the error wont allow me to use ToString, is there any way around this?
I believe that you may be incorrectly making use of ToString().
Are you trying to retrieve the following formatted result?
hh:mm:ss
If so, you might find this approach worthy of consideration:
int hour = Convert.ToInt32(HourAlarmCB.SelectedItem);
int minute = DateTime.Today.Minute;
int second = DateTime.Today.Second;
label2.Content = String.Format("{0:D2}:{1:D2}:{2:D2}", hour, minute, second);
See String.Format for converting an arbitrary list of variables into a single formatted string.
For a description of "D2", see Standard Numeric Format Strings.
Update: First, note that DateTime.Today returns "an object that is set to today's date, with the time component set to 00:00:00."
Now, in reference to your question, to output AM or PM, use the t standard format string:
DateTime date = DateTime.Today; // time is '00:00:00'
int hour = Convert.ToInt32(HourAlarmCB.SelectedItem);
int minute = date.Minute; // always '0'
int second = date.Second; // always '0'
label2.Content = String.Format("{0:D2}:{1:D2}:{2:D2} {3:t}",
hour, minute, second, date); // for example: '08:00:00 AM'
So the end result is me having to the HourAlarmCB variable to a string
if ((e.Result.Text == "set a alarm") || (e.Result.Text == "set an alarm"))
{
Jarvis.Speak("setting alarm");
string HourAlarmStr = HourAlarmCB.SelectedItem.ToString();
label2.Content = DateTime.Today.Hour.ToString(HourAlarmStr) + ":" + DateTime.Today.Minute.ToString("54") + ":" + DateTime.Today.Second.ToString("00");
label2.Opacity = 100;
dispatcherTimer2.Start();
}
Okay i got a way to calculate the time Difference between 2 files, or rather 2 "dates".
And it works, however, if the time difference is a day, meaning one starts at, let´s say 23:00, and the other 01:20 the next day, it will fail and think it´s behind rather than just 2 hours in front.
Here is the code:
private void button1_Click(object sender, EventArgs e)
{
try
{
DateTime firstDt;
DateTime lastDt;
if (DateTime.TryParseExact(First.Text, "yyyy-MM-dd HH-mm-ss-fff", CultureInfo.InvariantCulture, DateTimeStyles.None, out firstDt)
&& DateTime.TryParseExact(Last.Text, "yyyy-MM-dd HH-mm-ss-fff", CultureInfo.InvariantCulture, DateTimeStyles.None, out lastDt))
{
var difference = lastDt.TimeOfDay - firstDt.TimeOfDay;
Console.WriteLine(difference);
CalcDiff.Text = "DelayAudio(" + difference.TotalSeconds.ToString("F3") + ")";
}
}
catch (Exception ex)
{
MessageBox.Show("TimeSpan Calculate: " + ex.Message);
}
}
Not really sure how to make it use the Day, as it seems like it should do it.
Just perform the subtraction on the full dates (rather than their time components):
var difference = lastDt - firstDt;
You can use the TimeSpan class to do that. For so, you need to substract a Date from another, like
TimeSpan ts = lastDate - startDate;
Console.Write(ts.Hours + ":" + ts.Minutes + ":" + ts.Seconds); // ts.ToString("HH:mm:ss") should work.
DateTime firstDt;
DateTime lastDt;
DateTime.TryParse(First.Text, out firstDt);
DateTime.TryParse(Last.Text, out lastDt);
TimeSpan difference = lastDt - firstDt;
CalcDiff.Text = "DelayAudio(" + difference.ToString()+ ")";
I have a registration form in my project on which I used three dropdownlists to enter day, month and year. In this date added to dropdownlist by codebehind method:
private void Add_Date()
{
ddl_dat.Items.Add(new ListItem("-Date-", "-1"));
for (int j = 0; j < 31; j++)
{
var newOption = new ListItem("" + (j + 1).ToString(), j.ToString());
ddl_dat.Items.Add(newOption);
}
}
And I add 12 months manually in month dropdownlist. I want user don't able to enter 29 feb or 31 april.
I done this by appling check before submitting the form:
if (ddl_year.SelectedIndex != -1 && ddl_dat.SelectedIndex != -1 && ddl_mon.SelectedIndex != 0)
{
if (ddl_mon.SelectedIndex == 2 && ddl_dat.SelectedIndex >= 28)
{
lbl_alert.Text = Convert.ToInt32(ddl_dat.SelectedValue)+ 1 + " Febuary Doesn't Exist";
}
}
Same method for all other months . But I don't think this is the correct method to solve this problem. Does anyone have any suggestions?
Apply this check before submitting form:
string str = ddl_dat.SelectedValue + "/" + ddl_mon.SelectedValue + "/"
+ ddl_year.SelectedValue;
DateTime dt;
if(!DateTime.TryParse(str, out dt))
// Invalid date - Show error
else
// Use date from dt here
If date is invalid TryParse will return false. Else you can use the resulting date from dt variable for further operation.
Since this is ASP.NET, you can use UpdatePanel to dynamically fill the contents of Date combobox on-the-fly through AJAX. You could then use DateTime.DaysInMonth() to find out the exact number of days in a month. You should update your Date combobox on both month and year dropdown's SelectedIndexChanged. This way your user won't be able to select incorrect dates in the first place, so no need to handle any errors.
Alternately there is Javascript calendar available in JQuery that could make your life easier.
DateTime.TryParse should help you.
DateTime dateValue;
string dateString = ddl_year.SelectedValue + "-" + ddl_mon.SelectedValue + "-" + ddl_dat.SelectedValue;
if (! DateTime.TryParse(dateString, out dateValue)) {
//Error...
}
I have 2 datetimepicker on form having joining and leaving date ,if i dont change these values than it throws exception on total_button_click,since its default value is today's date ,so i want to enable total_button only when datetimepicker value gets changed,can i use any property of datetimepicker for this purpose ,below is the code for total_button
private void Total_button_Click(object sender, EventArgs e)
{
int remain, re, d, r;
string oday;
decimal sum = dataGridView1.Rows.OfType<DataGridViewRow>()
.Sum(row => Convert.ToDecimal(row.Cells["Money"].Value));
// total amnt drawn
textBox1.Text = sum.ToString();
d = int.Parse(textBox3.Text);
int div = d / 30;
// 1 day payment
oday = div.ToString();
textBox6.Text = (dateTimePicker2.Value - dateTimePicker1.Value).TotalDays.ToString("#");
re = int.Parse(textBox6.Text) * int.Parse(oday);
// total days paymnt
textBox7.Text = re.ToString();
r = int.Parse(textBox7.Text) - int.Parse(textBox1.Text);
// total payment -drawn i.e to b payed
textBox8.Text = r.ToString();
}
Use the DateTimePickerEvent ValueChanged http://msdn.microsoft.com/de-de/library/system.windows.forms.datetimepicker.valuechanged.aspx . If the event gets invoked, you can enable your button.
To get this working you would need the ValueChanged event of the datetimepicker
dateTimePicker1.ValueChanged += new EventHandler(dateTimePicker1_ValueChanged);
Now this would fire in general even if you select the current date from the Calender displayed, to avoid that set the format to only Date and avoid the time component like
dateTimePicker1.Value = DateTime.Today;
Now this would fire only if you change the date and within this you can enable your required button