const double PERCENT = 0.25;
DateTime t1 = Convert.ToDateTime(txtB_StartT.Text);
DateTime t2 = Convert.ToDateTime(txtB_EndT.Text);
TimeSpan ts = t1.Subtract(t2);
I cant seem to get this to parse into a DateTime
double tsMin = Convert.ToDouble(ts);
double tsMinTot = ts.TotalMinutes;
short tsMinPercent = (short)(((double)tsMinTot) * PERCENT);
double tsAndPercentTot = tsMinPercent + tsMinTot;
My goal here was to find a timediff, find what 25% of that timediff is and add it to the timediff.
DateTime newTimeMinTot = Convert.ToDateTime(tsAndPercentTot);
int hours = newTimeMinTot.Hour;
int minutes = newTimeMinTot.Minute;
An attempt to get a calculated new Datetime
string newTimeStrg = string.Format("{0:d1}:{1:d2}", hours, minutes);
txtB_NewDelivT.Text = newTimeStrg;
Attempt to output new DateTime to TextBox.
Someone please explain. How can I make the user input in military time and make this work.
Do it like this:
const double PERCENT = 0.25;
DateTime t1 = Convert.ToDateTime(txtB_StartT.Text);
DateTime t2 = Convert.ToDateTime(txtB_EndT.Text);
TimeSpan ts = t1.Subtract(t2);
long tsMinPercent = ts.Ticks + (long)(ts.Ticks * PERCENT);
var tsAndPercentTot = TimeSpan.FromTicks(tsMinPercent);
string newTimeStrg = string.Format("{0:d1}:{1:d2}", tsAndPercentTot.Hours, tsAndPercentTot.Minutes);
txtB_NewDelivT.Text = newTimeStrg;
Here I am using DateTime.Ticks to calculate percentage of time of difference and TimeSpan.FromTicks to find DateTime again from calculated percentage DateTime.
Instead using TextBox you can use TimePicker.
to force your date/datetime format
DateTime mydate = DateTime.ParseExact(TextBox1.Text.Trim(), "dd/MM/yyyy", null);
Based on your comment where you write that the input values are "0945" and "1445", I suggest you to replace your TextBox controls with DateTimePicker controls.
Just to have them display values as you are doing right now, you'll have to set some properties as I show you here.
picker.Format = DateTimePickerFormat.Custom;
picker.CustomFormat = "HHmm";
picker.ShowUpDown = true;
later, the picker.Value will return a whole date with time, where minutes and seconds will resemble the input values.
You can obvously set the properties' values from the designer.
Regards,
Daniele.
Since I don't have your form, I'll leave out the UI interaction. Here's how you can parse an input stream. I've show how to parse a hh:mm format, as well as a hhmm format:
var start = TimeSpan.ParseExact("10:00", "hh\\:mm", CultureInfo.InvariantCulture);
var finish = TimeSpan.ParseExact("1100", "hhmm", CultureInfo.InvariantCulture);
Once you have the start and finish, all we have to do is the math. We'll create a new TimeSpan from the ticks (the smallest unit of measurement on a TimeSpan) multiplied by our percentage (0.25). Then we just add the adjustment to our start time and we're done! You can then assign that into where ever you need the output.
var diff = finish - start;
var adjustment = TimeSpan.FromTicks((long)(diff.Ticks * 0.25));
var adjustedStart = start + adjustment;
You can run the code out at dotNetFiddle. I've included output there so you can see the intermediate results along the way.
Ok well i took a different approach and it worked out fairly easy.
I'm not sure if I'm allowed to answer my own question but i figure it
will help someone with the same issue i had.
// Set Constant values.
const double PERCENT = .25;
const int HUN_PART = 100, SIXTY = 60, one = 1;
// Parse start time textbox value as int
// Calculate start time hours and minutes
int sT = int.Parse(textBox1.Text);
int sH = sT / HUN_PART;
int sM = sT % HUN_PART;
// Calculate total start time in minutes
int sH_M = sH * SIXTY;
int sTotM = sH_M + sM;
// Parse end time textbox value as int
// Calculate end time hours and minutes
int eT = int.Parse(textBox2.Text);
int eH = eT / HUN_PART;
int eM = eT % HUN_PART;
// Calculate total end time in minutes
int eH_M = eH * SIXTY;
int eTotM = eH_M + eM;
// Calculate time difference in minutea
// Calculate percent of time difference
double dT_M = Convert.ToInt32(eTotM - sTotM);
int perc = Convert.ToInt32(dT_M * PERCENT);
// Calculate new arrival time in total min then in hours
double newD_M = perc + eTotM;
double newD_H = newD_M / SIXTY;
// Calculate new arrivaltime in remaining minutes
double nD_H_Convert = Math.Truncate(newD_H);
int nD_H = Convert.ToInt32(nD_H_Convert);
int nD_Hours = nD_H * HUN_PART;
double nD_Min = nD_H * SIXTY;
int nD_M = Convert.ToInt32(newD_M - nD_Min);
int newDeliveryTime = (nD_H * HUN_PART) + nD_M;
// Put values for new arive time hours and minutes in appropriate string format
string newTime = string.Format("{0:d4}", newDeliveryTime);
// Output arrival time string in textbox
textBox3.Text = newTime;
I was apparently trying to do more than was actually required, so by using a few simple calculations the issue was resolved.
Thank you for the help everyone.
Related
here is my code
private void button2_Click(object sender, EventArgs e)
{
try
{
ans = double.Parse(txtb1.Text) - double.Parse(txtb2.Text);
string time = ans.ToString();
double seconds = TimeSpan.Parse(time); // Duration is not working
label1.Text = seconds.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
i am trying to round up from after the point i.e if its greater than or equals to 60 it should add one to the integer and subtract it from the mantissa(decimal)
what i mean is that if i have a value of 1.70, i should have 2.10 i.e 2hrs 10min
If you want to manipulate the double value of 1.70 to Hours and minutes with your logic you should do the following.
var dbl = 1.70;
var hours = Math.Floor(dbl);
var minutes = (dbl - hours) * 100;
var ts = TimeSpan.FromHours(hours).Add(TimeSpan.FromMinutes(minutes));
Console.WriteLine("{0}h {1}min", Math.Floor(ts.TotalHours), ts.Minutes);
If your value is actually "{Hours}.{Minutes}" and could have "100.500" for 100hours 500minutes then you would need to change how you parse the value to get hours and minutes.
You might be looking for Math.Ceiling(ans).
It will always round up, even if the decimal value is below 0.5
If you want to correct a time string from the format that you posted I would suggest to use this method:
public static double correctTime(string commaTime)
{
double d = Convert.ToDouble(commaTime, CultureInfo.InvariantCulture);
int basis = (int)d;
// if the number after the comma is larger than 0.6 then just add 0.4
return d - basis > 0.6 ? d = d + 0.4 : d;
}
As for the conversion into a TimeSpan you need to get your number into the right format:
string s = "1.7";
double cor_s = correctTime(s);
string time = cor_s.ToString("00.00").Replace('.', ':'); // or
now you can parse it into a TimeSpan:
TimeSpan t = TimeSpan.Parse(time);
or if you want only the seconds:
double total_seconds = TimeSpan.Parse(time).TotalSeconds;
I hope I understood your problem correctly
I get from TimeSpan.TotalHours 24,75 hours.
How can I convert this to get the full and not roundes hours (=24) plus the minutes (0,75hours = 45 minutes)? So the result should be hours = 24 and minutes = 45
I tried to convert it to string and make substring but I would like to know if there is a better way than this.
string test = Reststunden.TotalHours.ToString().Substring(Reststunden.TotalHours.ToString().IndexOf(","),3).Replace(",", "");
double Minuten = Convert.ToInt16(test) * 0.6;
Well just round the total hours appropriately by casting, and then use the Minutes property:
int hours = (int) timeSpan.TotalHours;
int minutes = timeSpan.Minutes;
If you'll ever have a negative TimeSpan, you should think about what you want the results to be and add appropriate tests - you may well find it doesn't do what you want with the simple code above.
How about:
var ts = TimeSpan.FromHours(24.75);
var h = System.Math.Floor(ts.TotalHours);
var m = (ts.TotalHours - h) * 60;
Or even:
var h = (int) (ts.TotalMinutes / 60);
var m = ts.TotalMinutes % 60;
I needed to display the total hours and minutes in the following format HH:mm.
With the help of the other answers I came to the following result:
var end = DateTime.Now;
var duration = end - StartUpTime;
var h = (int)(duration.TotalMinutes / 60);
var m = (int)(duration.TotalMinutes % 60);
var text = $"{h:D2}:{m:D2}";
hey all so I'm having a hard time with my code when trying to display in a textbox.. testing goes well till i try something along the lines of a start time being a higher number than the end time when i do it displays something like this on my program -04-30 but on the example program it shows -0430.
How can i get it to display properly?
My last three lines of code read. (this is for a programming project for my college class. i have my form program i have developed and then an example one. for the program it asks to give a start time, and end time. and the program calculates a new arrival time due to construction in the area(which makes the original trip 25% longer)
int endTimeHours = (int) totalTimeMins / DIVISOR_SIXTY;
int endTimeMins = (int)totalTimeMins - (endTimeHours * DIVISOR_SIXTY);
//display answer in textbox for user to see and understand.
textBoxNewArrival.Text = string.Format("{0:d2}" + "{1:d2}", endTimeHours, endTimeMins);
entire code is;
`// Declare Constants
const int HUNDRED = 100, DIVISOR_SIXTY = 60;
const double CONSTRUCTION = 1.25;
//get start time from user
int startTime = int.Parse(textBoxStart.Text);
//get end time from user
int endTime = int.Parse(textBoxEnd.Text);
//separate and convert to hours and minutes for start time
int hoursStart = startTime / HUNDRED;
int minsStart = startTime % HUNDRED;
int totalMinutesStart = (hoursStart * DIVISOR_SIXTY) + minsStart;
//separate and convert to hours and minutes for end time
int hoursEnd = endTime / HUNDRED;
int minEnd = endTime % HUNDRED;
int totalMinutesEnd = (hoursEnd * DIVISOR_SIXTY) + minEnd;
//find total duration by subtracting total end times in minutes from total start time in minutes
int totalDuration = totalMinutesEnd - totalMinutesStart;
//take the totalDuration or time between start and end and multiply by 1.25 for construction time.
double construction = totalDuration * CONSTRUCTION;
//take totalmintuesstart from begining and add construction.
double totalTimeMins = totalMinutesStart + construction;
//find and convert the answers into hours and minutes total
int endTimeHours = (int) totalTimeMins / DIVISOR_SIXTY;
int endTimeMins = (int) totalTimeMins - (endTimeHours * DIVISOR_SIXTY);
//display answer in textbox for user to see and understand.
textBoxNewArrival.Text = string.Format("{0:d2}" + "{1:d2]", endTimeHours, endTimeMins.ToString().Remove(0, 1));
`
Just keep the sign of the first value, and always use the absolute value of the second?
textBoxNewArrival.Text = string.Format("{0:d2}" + "{1:d2}", endTimeHours, Math.Abs(endTimeMins));
For a quick solution you should try doing this in the textBox assignation:
textBoxNewArrival.Text = string.Format("{0:d2}" + "{1:d2}", int.Parse(endTimeHours, endTimeMins.ToString().Remove(0,1)));
this is the test i did to check if this time worked:
class Forms
{
public static void Main(string[] args)
{
int endTimeHours = -4;;
int endTimeMins = -30;
string temp = string.Format("{0:d2}" + "{1:d2}", endTimeHours, int.Parse(endTimeMins.ToString().Remove(0, 1)));
Console.WriteLine(temp);
}
}
i have:
jobElement.CreationDate = jobElement.CreationDate + TimeSpan.FromHours(24.0);
i would like to have not strictly 24 hours, but with +- 10 seconds Buffer. like 23.59.10 and 00.00.10
hot to reach that with c#?
This will generate CreationDate + 23:50 and CreationDate + 24:10 with equal probability:
Random random = new Random();
TimeSpan buffer = TimeSpan.FromSeconds(10);
TimeSpan span = TimeSpan.FromHours(24.0);
// 50% of the time do this
if(random.Next() % 2 == 0)
{
span += buffer;
}
// The rest of the time do this
else
{
span -= buffer;
}
jobElement.CreationDate = jobElement.CreationDate + span;
What do you need to do with that?
If you need to any comparison create custom class with overwritten equality operators.
I'm not 100% sure what you want here but I'll give it a shot
DateTime dt1 = DateTime.Now;
DateTime dt2 = DateTime.Now.AddDays(1).AddSeconds(8);
These two are now 24 hours and 8 seconds apart.
Then if you want to see if they are "almost" 24 hour appart, you can do something like this:
if( Math.Abs((dt1-dt2.AddDays(-1))) < 10 ){
//dt2 is 24 after dt1 +- 10 seconds
}else{
//they are not
}
First time (00.00.00) of current date -/+ 10 secs would be:
DateTime dateFrom = jobElement.CreationDate.Date.AddSeconds(-10);
DateTime dateTo = jobElement.CreationDate.Date.AddSeconds(10);
Is that it?
I'll add this variant. It's different from others because it isn't "second based" but "tick" based (the tick is the smallest time that a TimeSpan/DateTime can compute)
const int sec = 10; // +/- seconds of the "buffer"
const int ticksSec = 10000000; // There are 10000000 Ticks in a second
Random r = new Random();
int rng = r.Next(-sec * ticksSec, sec * ticksSec + 1); // r.Next is upper-bound exclusive
var ts = TimeSpan.FromHours(24) + TimeSpan.FromTicks(rng);
jobElement.CreationDate = jobElement.CreationDate + ts;
There are limits in the Random class (it can't generate a long, and generating a "constrained" long (a long with maxValue = x) is non-trivial based only on the Random class, so this will work for up to 3 minutes and something of "buffer" (214 seconds to be more exact).
If you want +/- 10 with all numbers between
Random r = new Random();
int x = r.Next(-10, 11);
var ts = TimeSpan.FromHours(24).Add(TimeSpan.FromSeconds((double)x));
jobElement.CreationDate = jobElement.CreationDate + ts;
Is there a tidy way of doing this rather than doing a split on the colon's and multipling out each section the relevant number to calculate the seconds?
It looks like a timespan. So simple parse the text and get the seconds.
string time = "00:01:05";
double seconds = TimeSpan.Parse(time).TotalSeconds;
You can use the parse method on aTimeSpan.
http://msdn.microsoft.com/en-us/library/system.timespan.parse.aspx
TimeSpan ts = TimeSpan.Parse( "10:20:30" );
double totalSeconds = ts.TotalSeconds;
The TotalSeconds property returns the total seconds if you just want the seconds then use the seconds property
int seconds = ts.Seconds;
Seconds return '30'.
TotalSeconds return 10 * 3600 + 20 * 60 + 30
TimeSpan.Parse() will parse a formatted string.
So
TimeSpan.Parse("03:33:12").TotalSeconds;
This code allows the hours and minutes components to be optional. For example,
"30" -> 24 seconds
"1:30" -> 90 seconds
"1:1:30" -> 3690 seconds
int[] ssmmhh = {0,0,0};
var hhmmss = time.Split(':');
var reversed = hhmmss.Reverse();
int i = 0;
reversed.ToList().ForEach(x=> ssmmhh[i++] = int.Parse(x));
var seconds = (int)(new TimeSpan(ssmmhh[2], ssmmhh[1], ssmmhh[0])).TotalSeconds;
//Added code to handle invalid strings
string time = null; //"";//"1:31:00";
string rv = "0";
TimeSpan result;
if(TimeSpan.TryParse(time, out result))
{
rv = result.TotalSeconds.ToString();
}
retrun rv;