All i have to do that just find the overtime of employee. The attendance sheet comes in CSV file and I've already saved the data to a table. The data Field hours is 12:10:00.0000000, and The Working Hour per day is 11:00:00.0000000. I've calculated the difference between these two times using Timespan.
DateTime date, hours, working_hours ;
TimeSpan ot_hours = TimeSpan.Zero;
TimeSpan tot_hours = TimeSpan.Zero;
if (hours > working_hours)
{
ot_hours = (hours - working_hours);
}
This code has set in a loop. after completing the loop I need to stote the total overtime into another variable. so wrote
tot_hours += tot_hours + ot_hours;
And next I need to find the salary overtime amount for the employee.
I've tried to convert this tot_hours(TimeSpan ) into Decimal. But it didn't work.
tothrsvalue = Convert.ToDecimal(tot_hours);
totalvalue = rate * tothrsvalue;
Anyone here.. Please have a look and help me.. Thanks in advance.
the total calculation part is given below:
decimal basics = Convert.ToDecimal(dtamt.Rows[0]["Amount"].ToString());
decimal rate = 0;
rate = ((basics / 30) / 8);
txtrate.Text = rate.ToString("0.000");
tothrsvalue = Convert.ToDecimal(total);
totalvalue = rate * tothrsvalue;
txtamount.Text = totalvalue.ToString("0.000");
amt = Convert.ToDecimal(txtamount.Text);
Parsing TimeSpan to decimal does not too much sense because time is not a numeric value at all.
But you can use it's TotalHours property which returns double.
var total = tot_hours.TotalHours;
Y need to to convert a TimeSpan to a decimal ? Its cannot be done becuase it isn't numeric.
You probably want tot_hours.TotalHours, which is a double that includes the fractional portion.
or tot_hours.TotalHours.ToString("#.00");
ot_hours is now a Timestamps difference = Seconds ! Divide them by 60 to make minutes
example : total = 2 minutes = 120 seconds etc.)
Related
This is now bugging me , i have tried to fix it for the past hour but still no luck!
I hope some one could spot what i'm doing wrong . here is my code:
var maxDays = 30;
DateTime today = DateTime.Now; //todays date
DateTime lastAction = '2017-03-07 12:47:58.967';
double totalDays = (lastAction - today).TotalDays;
var days = Math.Round(totalDays);
if(days > maxDays)
{
//never hits this even though days is greater than max days ..i'm so confused
}
what am i doing wrong?
Duplicate problem as here:
C# Number of days between two dates problem
Timespan.TotalDays can be negative. So in your case it is almost guaranteed that lastAction - today will be a negative number, and so will always be less than 30.
If you only care about the absolute value of days, use Math.Abs otherwise re-arrange so that you are subtracting lastAction from today (today - lastAction).
Note that due to rounding, your condition will still not be triggered if there is less than 1 day difference.
Is it possible you are subtracting a larger value (today) from a small value (lastaction) which should result in a negative number making days negative?
That and you do need to do an explicit parse on the string to make it a date:
DateTime lastAction = DateTime.Parse("2017-03-07 12:47:58
.967");
Couple of things.
First you cant convert a string to DateTime like that. You should do something like this instead. DateTime lastAction = DateTime.Parse("2017-03-07 12:47:58.967");
Second, Just as #MikeS said, you are subtracting the lastAction from Today, which is resulting in a negative number (in this case its like -173). You should flip that statement. double totalDays = ( today - lastAction).TotalDays;
Your whole section should look something like this.
var maxDays = 30;
DateTime today = DateTime.Now; //todays date
DateTime lastAction = DateTime.Parse("2017-03-07 12:47:58.967");
double totalDays = ( today - lastAction).TotalDays;
var days = Math.Round(totalDays);
if (days > maxDays)
{
// now this is hit
}
Thanks for the help. I did something stupid .. I had
double totalDays = (lastAction - today).TotalDays; // returns -176
changed my code to:
double totalDays = (today - lastAction).TotalDays; //returns 176
Your first problem:
You didn't parse the string to DateTime.
DateTime lastAction = Convert.ToDateTime("2017-03-07 12:47:58.967");
Your second problem:
You were receiving a negative value, and checking if it's bigger.
var days = (Math.Round(totalDays)) * (-1);
Like this, it should work.
I am converting minutes into hours. So if I have minutes = 12534. The result should be 208:54. The below code fails to bring this result.
TimeSpan spWorkMin = TimeSpan.FromMinutes(12534);
string workHours = spWorkMin.ToString(#"hh\:mm");
Console.WriteLine(workHours);
The result is 16:54.
How to get it correct?
var totalMinutes = 12534;
Console.WriteLine("{0:00}:{1:00}", totalMinutes / 60, totalMinutes % 60);
Or
var totalMinutes = 12534;
var time = TimeSpan.FromMinutes(totalMinutes);
Console.WriteLine("{0:00}:{1:00}", (int)time.TotalHours, time.Minutes);
See https://dotnetfiddle.net/gYEsj2 to play with this
The correct way to use is not using the ToString overload of DateTime – because there is no possibility to show the TotalHours there – but the string.Format method:
string.Format("{0:00}:{1:00}", (int)spWorkMin.TotalHours, spWorkMin.Minutes);
You need use TimeSpan.TotalHours Property
The TotalHours property represents whole and fractional hours, whereas the Hours property represents whole hours.
TimeSpan spWorkMin = TimeSpan.FromMinutes(12534);
string workHours = spWorkMin.ToString(#"hh\:mm");
Console.WriteLine(spWorkMin.TotalHours);
https://dotnetfiddle.net/JRCLra
The format specifier hh will show the hour part, which is not the total hours. You have to manually create a string using TotalHours cast into ints to show it as you want and add the minutes to that.
TimeSpan spWorkMin = TimeSpan.FromMinutes(12534);
string workHours = string.Format("{0}:{1}", (int)spWorkMin.TotalHours, spWorkMin.Minutes);
Console.WriteLine(workHours);
From MSDN documentation:
The "hh" custom format specifier outputs the value of the TimeSpan::Hours property, which represents the number of whole hours in the time interval that is not counted as part of its day component.
One quick way of getting the result you want would be something like the following:
TimeSpan spWorkMin = TimeSpan.FromMinutes(12534);
string workHours = string.Format("{0}:{1:00}", (int)spWorkMin.TotalHours, spWorkMin.Minutes);
Console.WriteLine(workHours);
Personnaly I use this:
public static double MinutsTohHours(int Minuti)
{
double Tempo = 0;
Tempo = ((double)(Minuti % 60) / 100);
var n = (double)Minuti / 60;
return Math.Floor((double)Minuti / 60) + Tempo;
}
using System;
var days = 1;
var hours = 23; //max 23
var min = 12; //max 59
var TotalMin = (days*24*60)+(hours*60)+min;
Console.WriteLine("TotalMins "+ TotalMin);
//return back to the original days,hours,minutes
var Days = (TotalMin/(24*60));
var _minutes = (TotalMin%(60*60));
var Hours = (_minutes/60);
var Minutes = _minutes - (Hours*60);
Console.WriteLine($"{Days} , {Hours} , {Minutes}");
I have done the following piece of code to add the Hours and thus calculate total number of hours.
string hour1="48.40";
string hour2 = "45.35";
TimeSpan ts = new TimeSpan(int.Parse(hour1.Split('.')[0]),int.Parse(hour1.Split('.')[1]),
0);
TimeSpan ts1 = new TimeSpan(int.Parse(hour2.Split('.')[0]),int.Parse(hour2.Split('.')[1]),
0);
Double total = (ts.TotalHours) + (ts1.TotalHours);
The problem here is when i add hour1 and hour2 the total comes as 64.25 which actually should have been 64.15
This is just one of the test case, if i put hour1= 40.00 and hour2= 40.10 than the value in the total comes as 80.166666666666657 which actually should have been 80.10
can anyone help me understand what am i doing wrong and what is the correct way to add HOUR and get total number of hours ?
Actually you're getting correct result - just mixing minutes and fractional parts of hours.
80 hrs 10 mins is 80 1/6 hours
64 hours 15 mins is 64 1/4 hours
It gets a little strange when you have timestamps put into strings. But if you need to do it like this, this code should work
string hour1="48.40";
string hour2 = "45.35";
//find total number of minutes for each hour above
int minutes1 = int.Parse(hour1.Split('.')[0])*60+int.Parse(hour1.Split('.')[1]);
int minutes2 = int.Parse(hour2.Split('.')[0])*60+int.Parse(hour2.Split('.')[1]);
//calculate back to hours and minutes and reassemble as a string
string result = (minutes1+minutes2)/60+"."+(minutes1+minutes2)%60;
And I hope you are expecting 94.15 and not 64.15 in your example above.
You may use next code to get result you would like to:
string hour1 = "48.40";
string hour2 = "45.35";
TimeSpan ts = new TimeSpan(int.Parse(hour1.Split('.')[0]), int.Parse(hour1.Split('.')[1]),
0);
TimeSpan ts1 = new TimeSpan(int.Parse(hour2.Split('.')[0]), int.Parse(hour2.Split('.')[1]),
0);
TimeSpan total = ts + ts1;
int hours = (int)total.TotalHours;
int minutes = total.Minutes;
in my application
Ex 1: Start time 12.30
(-)End time 16.00 here i get the value as 3.7 but i need to show this 3.7 as 3.5 in my application
Ex 2: Start time 12.00
(-)End time 16.00 here i get the value as 4.0 here there is no need to alter the value
(1.7,2.7,3.7,4.7,.... etc ) as to be represented as(1.5,2.5,3.5,4.5,.. etc )
so how to write an function for this where if the vale contains(1.7,2.7) i should change to 1.5,2.5
or if it contains 1.0,2.0 then there is no need to replace any value?
This extension method ought to do the job:
public decimal RoundToNearestHalf(this decimal value)
{
return Math.Round(value * 2) / 2;
}
var num1 = (3.7).RoundToNearestHalf(); // 3.5
var num1 = (4.0).RoundToNearestHalf(); // 4.0
I've used the decimal type in the code because it seems you want to maintain base 10 precision. If you don't, then float/double would do just as well, of course.
Use the DateTime type. Subtracting DateTime types returns a TimeSpan. Use TimeSpan.TotalHours to get your result. E.g.:-
var x = DateTime.Parse("12:30");
var y = DateTime.Parse("16:00");
Console.WriteLine((y - x).TotalHours);
Use DateTime type to work with time. Example:
string time1 = "12:30";
string time2 = "16:00";
TimeSpan diff = DateTime.Parse(time2)-DateTime.Parse(time2);
string diffString = diff.ToString("hh:mm"); // will be 03:30
Multiply hours with 60 and add minutes. You'll get total number of minutes.
12hours and 30 minutes = 720 + 30 = 750 minutes.
16 hours = 960 minutes.
Subtract the first value from the other and divide it by 60
(960 - 750) / 60 = 210 / 60 = 3.5
You should use TimeSpan and round it off:
TimeSpan startTime = new TimeSpan(12, 30, 0);
TimeSpan endTime = new TimeSpan(16, 0, 0);
TimeSpan span = endTime - startTime;
double totalHours = span.TotalHours;
double roundedToHalf = Math.Round(totalHours * 2) / 2;
Console.WriteLine(roundedToHalf);
UPDATE:
If the start and end time are from different dates, you should use DateTime for startTime and endTime.
If the values in your question represent times you can't do decimal arithmetic with them and expect time values as results.
You need to manipulate the values as times
I don't know C#, but it must have some time functions.
Have the times as DateTime then use Timspan to find the difference between the two times?
Times are not integers or floats. You can't work with them as if they are - you wouldn't try to do integer math using the String class, would you?
DateTime and TimeSpan are you friends for this kind of data manipulation.
You can use the C# Floor and Ceil method of the Math Class. Read more about it in the below URLs:
http://msdn.microsoft.com/en-us/library/system.math.ceiling(VS.71).aspx
http://dotnetperls.com/math-floor
string i = "2.0";
if (i == "2.3" || i == "3.3" || i == "4.3")
{
string strReplace = i.Replace(".3", ".5");
}
else
{
string strReplace = i;
}
I have a minute value and i want to have to 2 string values one with how many hours and the other with the minutes, e.g.:
Value - 121 minutes
string hours = 2
string minutes = 1
Value - 58 minutes
string hours = 0
string minutes = 58
How can I work this out in C#?
var span = System.TimeSpan.FromMinutes(121);
var hours = ((int)span.TotalHours).ToString();
var minutes = span.Minutes.ToString();
The ToString() is because you asked for string values ...
TotalHours are the complete hours in the TimeSpan, they can be more than 24 (whereas the "Hours" field has a maximum of 24)
Oh, and on second thought: Why use the TimeSpan and not calculate it yourself? Because TimeSpan is already there debugged & tested by Microsoft, it has a nice clean interface (looking at the code you easily see whats going on without having to follow a calculation mentally) and it easily extends to further solutions. (Have the input in seconds? Use TimeSpan.FromSeconds(). Want the days? Use span.TotalDays ...)
Update:
I just noticed mistake in my answer: TotalHours returns a fractional value of all the hours, so we have to truncate it to an integer before converting it to a string.
Use a Timespan struct and its Parse method.
int value = 121;
int hours = value / 60; // 2
int minutes = value % 60; // 1
string strHours = hours.ToString();
string strMinutes = minutes.ToString();
int value = 121;
int hours = value / 60;
int minutes = value % 60;
int value = 121;
TimeSpan timeSpan = TimeSpan.FromMinutes(value);
// gives you the rounded down value of 2
int hours = timeSpan.Hours;
// gives you the minutes left of the hour
int minutes = value - (hours * 60);