I have 2 datetime pickers and i want to display number of days between them on a text box if a user selects a date.. the problem with my code is that its not giving me correct answers and the time span doesnt seem to work.. i dont know where im going wrong thats why i asked for assistance.
I hope that explained better, please bear with me, its my first time to be on this site so im not familiar with the controls, sending stuff and updating
When i choose different dates it gives me answer 10.999998008713 days instead of 11 days and i dont know if i need to do math roundup
private void btnCalc_Click(object sender, EventArgs e)
{
DateTime start = ArrivalDate.Value;
DateTime finish = DepartureDate.Value;
TimeSpan numberOfNights = finish-start;
double TotalDays= numberOfNights.Days;
txtBoxNum.Text = (numberOfNights.ToString());
}
private void ArrivalDate_ValueChanged(object sender, EventArgs e)
{
DepartureDate.Value = ArrivalDate.Value.AddDays(1);
}
private void DepartureDate_ValueChanged(object sender, EventArgs e)
{
// setting messagebox to a sensible default message if no date or wrong date picked
if (DepartureDate.Value < ArrivalDate.Value)
{
MessageBox.Show("Cannot be less than previous date");
DepartureDate.Value = ArrivalDate.Value.AddDays(1);
}
else
{
double Days = (DepartureDate.Value - ArrivalDate.Value).TotalDays;
txtBoxNum.Text = Days.ToString();
return;
You need to get only the date part from your date picker:
DateTime start = ArrivalDate.Value.Date;
DateTime finish = DepartureDate.Value.Date;
Otherwise you also get time which interferes with your calculations.
Also, to display number of days as integer, use:
int TotalDays = numberOfNights.Days; // Days is int anyway
txtBoxNum.Text = TotalDays.ToString();
Or simply
txtBoxNum.Text = numberOfNights.Days.ToString();
You can actually put the whole code into one line:
txtBoxNum.Text = new TimeSpan(DepartureDate.Value.Date.Ticks - ArrivalDate.Value.Date.Ticks).Days.ToString();
Related
My code is:
public Form1()
{
InitializeComponent();
Core.Initialize();
this.KeyPreview = true;
this.KeyDown += new KeyEventHandler(ShortcutEvent);
oldVideoSize = videoView1.Size;
oldFormSize = this.Size;
oldVideoLocation = videoView1.Location;
//VLC stuff
_libVLC = new LibVLC();
_mp = new MediaPlayer(_libVLC);
videoView1.MediaPlayer = _mp;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
TimeSpan Percent = TimeSpan.FromSeconds(_mp.Position);
label1.Text = Percent.ToString(#"hh\:mm\:ss");
TimeSpan time = TimeSpan.FromSeconds(_mp.Time);
label2.Text = time.ToString(#"hh\:mm\:ss");
TimeSpan length = TimeSpan.FromSeconds(_mp.Length);
label3.Text = length.ToString(#"hh\:mm\:ss");
}
The percentage part doesn't work at all, and the current time part doesn't run correctly and doesn't tick in a real clock but according to an illogical division, and the return of the total time of the video doesn't make sense in its conversion to the clock string.
It seems that the conversion doesn't fit here, or there is another code or an alternative, so I'm asking someone who has something that returns what I'm looking for, that is, how long the video actually is, and where it is now, in a way that looks like a clock, that is: .ToString(#"hh\ :mm:ss").
Thank you!
I know this is a little late, but your last question wasn't answered yet.
As mentioned in the comments you need to use milliseconds instead of seconds.
So, for your example above you would just need to change the TimeSpan method used like so
private void timer1_Tick(object sender, EventArgs e)
{
TimeSpan time = TimeSpan.FromMilliseconds(_mp.Time);
label2.Text = time.ToString(#"hh\:mm\:ss");
TimeSpan length = TimeSpan.FromMilliseconds(_mp.Length);
label3.Text = length.ToString(#"hh\:mm\:ss");
}
I've removed the position label because that is just a float that will be 0 to 1 so not useful in the TimeSpan.
Just can't get it with datepicker validation.
I have datepicker From and datepicker To, so I want to prevent the user from doing some kung fu and seting datepicker From to be bigger than datepicker To, I've bumped across some questions but couldn't find the answer, so I've tried doing the easiest way I could think of:
Set MaxDate property for datepicker from in form_load event
private void Form1_Load(object sender, EventArgs e)
{
datepickerFrom.MaxDate = datepickerFrom.Value;
}
Then do the same for value_changed event
private void datepickerFrom_ValueChanged(object sender, EventArgs e)
{
datepickerFrom.MaxDate = datepickerFrom.Value;
}
This was easy and fine, only few lines of code, and I've only needed datepickerFrom_ValueChanged event, but recently I've tried typing date into datepicker insted of selecting it, and then all hell broke loose.
So I came to some solution for validation, instead of setting MaxDate property, I've tried this.
private void dtFrom_ValueChanged(object sender, EventArgs e)
{
DateTime from = datepickerFrom.Value;
DateTime to = datepickerTo.Value;
int year= from.Year > to.Year ? to.Year : from.Year;
int month = from.Month > to.Month ? to.Month : from.Month;
int day = from.Day > to.Day ? to.Day : from.Day;
int hour = from.Hour > to.Hour ? to.Hour : from.Hour;
int minute = from.Minute > to.Minute ? to.Minute : from.Minute;
int second = from.Second > to.Second ? to.Second : from.Second;
//setting datepicker value
datepickerFrom.Value = new DateTime(year, month, day, hour, minute, second);
}
This works fine, but feels like bit of headache, and I have to do this for datepickerTO_ValueChanged event also, sure I could make one method and call it two times, but still feels like there is a batter way for this, so any suggestions?
Thank you for your time
Solution 1:
You can handle datePickerTo close event and do something like:
private void dateTimePickerTo_CloseUp(object sender, EventArgs e)
{
DateTime fromdate = Convert.ToDateTime(dateTimePickerFrom.Value);
DateTime todate1 = Convert.ToDateTime(dateTimePickerTo.Value);
if (fromdate > todate1)
//Error
}
You can also use DateTime.Compare whcih get two date
like
int result = DateTime.Compar(dateTimePickerFrom.Value ,dateTimePickerTo.Value);
if result is 1 means From date is earlier, see this link.
Note1:
but as you said if user type in From or To textboxes then closeup event never fire so you need compare them in where you want to process
such as button click.
Note2:
As #Sinatr comment if Value is DateTime then don't need to convert it so the code would be like:
if (dateTimePickerFrom.Value >dateTimePickerTo.Value)
//Error
Your proposal would lead to a horrible interface. Suppose the following case:
From = 1 jan 2000
To = 1 feb 2000
User wants to change both values to 2010. He starts with the from value:
From = 1 jan 2010
Now he wants to change the TO value to 1 feb 2010. Alas, he can't.
Proper usage would be: add some button with which the operator can affirm he has changed all data, start checking it and update. In windows this button is usually named Apply Now or OK. Why deviate from this windows standard.
private void OnFormLoading(object sender, ...)
{
this.FromDate.MinValue = ... // use the real absolute min value you want ever to allow
this.FromDate.MaxValue = ...;
this.ToDate.MinValue = ...;
this.ToDate.MaxValue = ...;
}
Don't do any checking as long as the operator is making changes. Strat checking the input values when he indicates that he finished making changes:
private void OnButtonApplyNow_Clicked(object sender, ...)
{
bool InputOk = CheckInput();
if (!inputOk)
{
ShowIncorrectInput(); // for instance using a MessageBox
}
}
Ok, so really weird problem I have here.
When I give ingaveBox a double value (0.5) and i press "bereken", it adds 5.0 to my gespaard variable. I have absolutely no clue how this happens. I know there's a small mistake somewhere but i just can't get it figured out, when I debug the value changes from the moment where i put the comment.
Thanks in advance!
public partial class MainWindow : Window
{
private string path = #"C:\Users\Ragtox\Documents\Spaarpot\Spaarpot\gespaard.txt";
private double vorigGespaard;
private double toegevoegd;
private double gespaard;
public MainWindow()
{
InitializeComponent();
ReadList();
}
void WriteList()
{
string[] createText = {gespaard.ToString()};
File.WriteAllLines(path, createText);
}
void ReadList()
{
string[] readText = File.ReadAllLines(path);
vorigGespaard = Convert.ToDouble(readText[0]);
vorigeBedragBox.Text = readText[0];
}
private void berekenButton_Click(object sender, RoutedEventArgs e)
{
vorigeBedragBox.Text = vorigGespaard.ToString();
gespaard = Convert.ToDouble(ingaveBox.Text) + vorigGespaard;
//this is where 0.5 goes to 5.0
gespaardBox.Text = gespaard.ToString();
WriteList();
ReadList();
}
private void saveButton_Click(object sender, RoutedEventArgs e)
{
WriteList();
}
}
As it's been said, the issue could well stem from the CultureInfo that your machine is running in. In general, you should ALWAYS persist and depersist values in an invariant culture so that values saved in one language can be read in successfully on another language.
Otherwise, if, say a Brazilian Portuguese (language code pt-br) user saves the value "123,456" (which is how one hundred and twenty three and four hundred and fifty six thousandths would be represented in Portuguese), a user reading it in, say, British English (language code en-gb) would interpret it as one hundred and twenty three thousand, four hundred and fifty six (i.e. a factor of one thousand out).
I've modified your code to use Double.ToString(CultureInfo.CurrentCulture) and Double.TryParse to save the values in the invariant culture.
void WriteList()
{
// save in invariant culture
string[] createText = {gespaard.ToString(CultureInfo.CurrentCulture)};
File.WriteAllLines(path, createText);
}
void ReadList()
{
string[] readText = File.ReadAllLines(path);
// read from invariant culture
bool parsed = double.TryParse(readText[0], NumberStyles.Any, CultureInfo.InvariantCulture, out vorigGespaard);
if ( !parsed )
throw new InvalidOperationException("Unable to parse " + readText[0] + " as a double");
// use the current culture to display the string
vorigeBedragBox.Text = vorigGespaard.ToString();
}
private void berekenButton_Click(object sender, RoutedEventArgs e)
{
vorigeBedragBox.Text = vorigGespaard.ToString();
// get the value from its representation in the current culture
gespaard = double.Parse(ingaveBox.Text) + vorigGespaard;
// use the current culture to display the string
gespaardBox.Text = gespaard.ToString();
WriteList();
ReadList();
}
This is a minor inconvenience compared to a real problem I have seen where the calendar was assumed to be Gregorian - this broke when I tried setting the culture to th (Thai) - they use the Buddhist calendar, which is ~543 years ahead. Its the year 2558 in that calendar - as you can imagine, not converting dates into UTC caused some problems...
I am developing an application called reminder using C# - visual studio 2010 . My Application reminds every event entered. Solution bellow works properly but I need to express this just using "datetimepicker" (calendar for date selection is not used)
MyRemindTime =dlg.MymonthCalendar.SelectionStart.AddHours(dlg.MyTimePicker.Value.Hour).AddMinutes(dlg.MyTimePicker.Value.Minute).AddSeconds(dlg.MyTimePicker.Value.Second);
timer1.Enabled = true;
private void timer1_Tick(object sender, EventArgs e)
{
if (MyRemindTime.CompareTo (DateTime.Now)<0)
{
timer1.Enabled = false;
MessageBox.Show("Alarm");
}
}
Could you please help me how to properly express MyRemindTime? I need to compare current date and time with datetimepicker. Time and datum has to be compared.
You can get the selected date/time as :
DateTime reminderTime = myDateTimePicker.Value;
And compare with the current time:
if(reminderTime < Datetime.Now)
//reminder time has passed
I am storing Datetime in a session as mentioned below:-
Session["LoggedInTime"] = System.DateTime.Now;
Then i m retrieving this value on a page load like this:-
DateTime _loggedInTime = Convert.ToDateTime(Session["LoggedInTime"]);
I debug the above code code and find that up to here the _loggedInTIme is showing the correct date which i m storing in it. After that i m calculating the time span like this:-
TimeSpan elapsedtimespan = System.DateTime.Now.Subtract(_loggedInTime);
int elapsedtime = Convert.ToInt32(elapsedtimespan.TotalSeconds);
I found while debugging the code that ,while subtraction the _loggedInTime = {1/1/0001 12:00:00 AM} and due to which i m not able to get exact elapsedtime .
Please help me to solve this issue as i m not getting why the _loggedInTime become {1/1/0001 12:00:00 AM} at calculating TimeSpan.
The following works fine for me. Since you prefix _loggedInTime with an underscore I'm assuming you declared it as an instance variable of the page itself.
private DateTime _loggedInTime;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["LoggedInTime"] == null)
Session["LoggedInTime"] = DateTime.Now;
_loggedInTime = Convert.ToDateTime(Session["LoggedInTime"]);
TimeSpan elapsedtimespan = DateTime.Now.Subtract(_loggedInTime);
int elapsedtime = Convert.ToInt32(elapsedtimespan.TotalSeconds);
}
I'm guessing that you are calculating the elapsed time at another time and not in the Page_Load as in the above example.
Make sure that on each post back you correctly load the elapsed time from the session before calculating the elapsed time. On the next post back the _loggedInTime is reset to the default value of a DateTime, being {1/1/0001 12:00:00 AM}.
I think you have something to the following setup.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["LoggedInTime"] == null)
Session["LoggedInTime"] = DateTime.Now;
_loggedInTime = Convert.ToDateTime(Session["LoggedInTime"]);
}
}
private void ButtonClick(object sender, ImageClickEventArgs e)
{
TimeSpan elapsedtimespan = DateTime.Now.Subtract(_loggedInTime);
int elapsedtime = Convert.ToInt32(elapsedtimespan.TotalSeconds);
}
Here I demonstrate it by handling a postback when a button is clicked. In that case the Page_Load does not load the LoggedInTime and the elapsed time is calculated incorrectly. To solve this, just remove the IsPostBack if statement in the Page_Load. Make sure you set the instance variable _loggedInTime each time you load the page, thus also on a postback.
Remark: Also check if you are on a server farm. If you are using multiple servers to handle your requests but have configured the wrong session mode (e.g. in process) then server A will store the session variable in its memory, but the redirect can be handled by server B, which doesn't know about server A's in-memory session store.
More information can be found on MSDN:
Session-State Modes
In process session state is the default, in a server farm scenario you can use the StateServer or SqlServer alternatives to share session state between the servers. Or you can write your own custom session state provider.
Since that's the default value for DateTime, I'm guessing you're attempting to use loggedInTime when it was not previously initialized in the Session object. In other words, my suggestion is to try something along these lines:
int elapsedtime = 0;
if (Session["LoggedInTime"] != null)
{
DateTime _loggedInTime = (DateTime)Session["LoggedInTime"];
TimeSpan elapsedtimespan = System.DateTime.Now.Subtract(_loggedInTime);
elapsedtime = Convert.ToInt32(elapsedtimespan.TotalSeconds);
}
else Session["LoggedInTime"] = System.DateTime.Now;