i have maded a counter which is a simple counter which starts from 00:00:00 and incremented in every seconds
i will provide my code for that
in the form load event i have written this
private DateTime startTime;
private void Form7_Load(object sender, EventArgs e)
{
startTime = DateTime.Now;
timer1.Start();
}
private void timer1_Tick(object sender, System.EventArgs e)
{
counter_label.Text = (DateTime.Now - startTime)
.ToString(@"hh\:mm\:ss");
}
the timer is set to 1000 means to 1 seconds so my timer works fine
but now i want to save the label.text to the setting of the winform which is located in the properties.settings.default
so i saved the text to that by
private void Form7_FormClosing(object sender, FormClosingEventArgs e)
{
DateTime st;
DateTime end;
st = Convert.ToDateTime(Properties.Settings.Default.datetime);
end = Convert.ToDateTime(counter_label.Text);
Properties.Settings.Default.datetime = counter_label.Text;
total_label.Text = (st + end ).ToString(@"hh\:mm\:ss");// this is not happening
Properties.Settings.Default.datetime = total_label.Text;
Properties.Settings.Default.Save();
}
the error is operand + cannot be applied to system.datetime and system.datetime
my intention is. when i save the text to the system properties. at the form closing event, the new updated result must be saved which is. the old text from the system.properties and the new fromt the counter_label. how can it be done?
Do not use setting of
stringtype to storeTimeSpanobject (as Habib already stated, subtraction or addition ofDateTimeobjects producesTimeSpan). You should create settings of typeSystem.TimeSpaninSettings.settingsfile (e.g. with name TotalTime).Saving:
Loading (here is trick – you are subtracting time which left from current time. So, if you have two minutes left, start time will be set for two minutes before you started applicatioin, like you never closed it):
So, you don’t need parsing any strings. Work with DateTime and TimeSpan, and let .NET to do all persisting work for you.
UPDATE (all code):
If it is first run of your application, then
Properties.Settings.Default.TotalTimewill return default value ofTimeSpan(which is zero time span). So, subtracting it from current time will return same value as current time.