I know this has been asked before but i couldn't figure out how to get the answers given working for my particular example. This is a WPF application written in C# and i'm trying to remove a number of minutes from a timespan.
So far i've got the application to figure out the duration by removing a Start Time from a Finish Time, but what i'm trying to do now is remove the number of minutes the user has entered into the form.
Here's the code so far
private void testcal_Click(object sender, EventArgs e)
{
string startTime = teststart.Text;
string finishTime = testfinish.Text;
// Trying to deduct this lunchTime var from the duration TimeSpan
string lunchTime = testlunch.Text;
TimeSpan duration = DateTime.Parse(finishTime).Subtract(DateTime.Parse(startTime));
testlabel.Text = duration.ToString(#"hh\:mm");
}
Edit - Updated to include private void
Are you asking how to subtract minutes from a TimeSpan?
If so try something like
TimeSpan ts = new TimeSpan().Subtract(TimeSpan.FromMinutes(30));
With user input it would be.
string startTime = teststart.Text;
string finishTime = testfinish.Text;
string lunchTime = testlunch.Text;
TimeSpan duration = DateTime.Parse(finishTime).Subtract(DateTime.Parse(startTime)).
Subtract(TimeSpan.FromMinutes(Int32.Parse(lunchtime)));
DateTime selectedDate = DateTime.Parse("10/09/2021");
DateTime now = DateTime.Now;
TimeSpan subtract = now - selectedDate;
subtract -= new TimeSpan(7, 0, 0, 0);
Related
I've got a thread that is only set to run within a certain period otherwise it's put on delay. From the time of running that threads of a certain Boolean value if true, then it should be delayed by X amount of time from current time to 18:00. Is there a quick way doing this in c#?
DateTime today = DateTime.Now;
DateTime tomorrow = today.Add(new TimeSpan(1,0,0,0));
DateTime tomorrowAtSix = new DateTime(tomorrow.Year, tomorrow.Month, tomorrow.Day, 18,0,0 );
TimeSpan diff = tomorrowAtSix.Subtract(DateTime.Now);
double hoursFromNow = 0d;
double minutesFromNow = 0d;
if(diff.TotalHours > 24d) // next 6pm is tomorrow
{
hoursFromNow = diff.TotalHours - 24d;
minutesFromNow = diff.TotalMinutes - (24d * 60d);
}
else // next 6pm is today
{
hoursFromNow = diff.TotalHours;
minutesFromNow = diff.TotalMinutes;
}
You can subtract DateTime objects which will return a TimeSpan
TimeSpan ts = DateTime.Now - new DateTime(2017, 1, 1);
I have added the calendar form and it won't let me select 2 dates. It assigns every click to the start date so when I try this it always tells me the difference is 1 and the start date is always changed to whatever my next click is?
Is it possible to have it default to today's date for the start date and then have every other click determine the end date? When I tried to assign today's date within the datechanged event handler it wouldn't let me change the month because it kept focusing on the startdate?
private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
{
numDays = Convert.ToInt32((monthCalendar1.SelectionEnd - monthCalendar1.SelectionStart).TotalDays);
MessageBox.Show("num " + numDays);
}
// Sets the Month Calenders Min & Max to days in current month.
DateTime dt = DateTime.Today;
DateTime firstDay = new DateTime(dt.Year, dt.Month, 1, 0, 0, 0);
DateTime lastDay = new DateTime(dt.Year, dt.Month, DateTime.DaysInMonth(dt.Year, dt.Month));
dateMonthCalender.MinDate = firstDay;
dateMonthCalender.MaxDate = lastDay;
The above will set min and max to days in current month
If you want to set the min to today
dateMonthCalender.MinDate = DateTime.Now;
Hope that helps..
Okay so declare two ints and assign one to selected day and the other to today and create yourself a method
int selectedDay;
int todayValue;
DateTime firstDay = new DateTime(dt.Year, dt.Month, 1, 0, 0, 0);
DateTime today = DateTime.Today;
string todayShort = today.ToShortDateString();
string thisDay = todayShort.Substring(0, 2);
todayValue = Convert.ToInt32(thisDay);
private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
{
// Shorten date format to day and assign it.
string dMC = dateMonthCalender.SelectionRange.Start.ToShortDateString();
string takeDMCDay = dMC.Substring(0, 2);
selectedDay = Convert.ToInt32(takeDay);
}
I need to compare two TimeSpan values bigger than 24 hours.
For that I use the following code
string startTime = textBox1.Text;
string endTime = textBox21.Text;
TimeSpan startTimet = new TimeSpan(int.Parse(startTime.Split(':')[0]), // hours
int.Parse(startTime.Split(':')[1]), // minutes
0);
TimeSpan endTimet = new TimeSpan(int.Parse(endTime.Split(':')[0]), // hours
int.Parse(endTime.Split(':')[1]), // minutes
0);
TimeSpan duration = endTimet.Subtract(startTimet);
label29.Text = duration.ToString();
If the values aren't bigger than 24H it's all ok, but if I have a value bigger than 24h the TimeSpan will appear like DD.HH.MM.SS.
For example:
endTimet = 32:15
startTimet = 02:00
duration = 1.06:15:00
And what I really need is the normal format like HH:MM, assuming the hours are greater than 24, getting the expected 30:15
Can anyone help me here?
Regards
Perhaps with this workaround:
TimeSpan duration = TimeSpan.FromHours(30);
string result = string.Format("{0}:{1}"
, duration.TotalHours
, duration.Minutes); // 30:00
Noda Time to the rescue!
string s1 = "123:45";
string s2 = "234:56";
DurationPattern p = DurationPattern.CreateWithInvariantCulture("H:mm");
Duration d1 = p.Parse(s1).Value;
Duration d2 = p.Parse(s2).Value;
Duration diff = d2 - d1;
string result = p.Format(diff); // "111:11"
In the below code i will get a list of time span values. I need to add all the time span values and that value has to be stored in string.How to achieve this i tried a lot but I can't find answer for this.
Thanks in Advance.
List<TimeSpan> objList = new List<TimeSpan>();
string totalIntervalTime = string.Empty;
private void Resume_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox2.Text))
{
textBox3.Text = DateTime.Now.ToLongTimeString();
//objPausetmr.Tick += new EventHandler(objPausetmr_Tick);
//objPausetmr.Stop();
tmrObj.Start();
DateTime pausetime = Convert.ToDateTime(textBox2.Text);
DateTime startTime = Convert.ToDateTime(textBox3.Text);
TimeSpan difference = pausetime - startTime;
string intervalDifference = difference.ToString();
richTextBox1.Text = intervalDifference;
TimeSpan tltTime = TimeSpan.Zero;
objList.Add(difference);
foreach (TimeSpan tmVal in objList)
{
tltTime.Add(tmVal);
}
totalIntervalTime = tltTime.ToString();
//MessageBox.Show(interval_Time.ToString());
}
else
{
MessageBox.Show("Please set the Pause time");
}
}
Assuming you want to add values of all time spans into single time span.
DateTime and TimeSpan are immutable structs. All operations using them return new instances. So you need to store result of operation in a TimeSpan value (normally just updating exisintg one is fine)
var totalTime = TimeSpan.Zero;
foreach (TimeSpan currentValue in objList)
{
totalTime = totalTime + currentValue;
}
Usage of + covered in details in TimeSpan.Addition Operator MSDN article.
Alternatively you can use Enumerable.Aggregate:
var totalTime = objList.Aggregate(
(accumulatedValue,current) => accumulatedValue + current);
You can try something like
string s = String.Join(",",objList.Select(x => x.ToString()));
Have a look at
String.Join Method
Enumerable.Select
Using objList.Select(x => x.ToString()) you can determine the format output you want
Span.ToString Method (String)
How to compare two DateTime to seconds?
var date1 = DateTime.Now;
var date2 = new DateTime (1992, 6, 6);
var seconds = (date1 - date2).TotalSeconds;
Do you mean comparing two DateTime values down to the second? If so, you might want something like:
private static DateTime RoundToSecond(DateTime dt)
{
return new DateTime(dt.Year, dt.Month, dt.Day,
dt.Hour, dt.Minute, dt.Second);
}
...
if (RoundToSecond(dt1) == RoundToSecond(dt2))
{
...
}
Alternatively, to find out whether the two DateTimes are within a second of each other:
if (Math.Abs((dt1 - dt2).TotalSeconds) <= 1)
If neither of these help, please give more detail in the question.
If you subtract one date from another, it returns a TimeSpan which has a TotalSeconds property. So:
double seconds = (Date1 - Date2).TotalSeconds;
DateTime start = DateTime.now;
DateTime end = DateTime.end;
TimeSpan dif = end - start;
dif will be of the form 0:0:0:0 where the third value is seconds.