my application in c# is on payroll management system...and i would like to have the work hours of each employee in variable ...for this i m using double ...suppose an employee works for 8 hours and 20 min ..then the entry will be like 8.20 in text box...so i am separating the part before decimal in one variable using`
var values = totaldays.ToString(CultureInfo.InvariantCulture).Split('.');
int firstno = int.Parse(values[0]);
int secondno = int.Parse(values[1]);`
so i m getting first variable accurately but if part after decimal contains zeros it not storing in "secondno" variable . the zeros get eliminated automatically and the result for 8.20 and 8.2 is same i.e., 8.2 .
but since the time is different one is 8 hours 20min and other is 8 hours 2min ..i want some solution to to do this ..please help me since my whole application is dependent on this.
If the user is entering hours and minutes, why not use a TimeSpan?
var input = "8.20";
var time = TimeSpan.ParseExact(input, #"h\.mm", null);
var hours = time.Hours; // 8
var minutes = time.Minutes; // 20
Further Reading
Custom TimeSpan Format Strings
If you really must store it as a decimal first, you can still manage using this:
var input = 8.20m;
var parts = input.ToString("0.00", CultureInfo.InvariantCulture).Split('.');
var hours = int.Parse(parts[0]); // 8
var minutes = int.Parse(parts[1]); // 20
But as Ellesedil points out, you'll have to decide how to handle values like 8.70.
Try something like this. This is off the top of my head:
int hours = Math.Floor(totaldays);
int minutes = (totaldays - Math.Floor(totaldays)) * 100;
You can just format double with f2 format specifier
double d = 8.20;
string str = d.ToString("f2", System.Globalization.CultureInfo.InvariantCulture)
int hour = int.Parse(str.Split('.')[0]);
int min = int.Parse(str.Split('.')[1]);
thats it you are done
Related
I want to parse the following input "10:05" in format "minutes:seconds" in seconds. So 10:05 should be 10 * 60 = 600 + 5 = 605. How can I manage to do this with code ?
Just split the string, parse the numbers, and do your calculation:
string s = "10:05";
var parts = s.Split(':');
int seconds = int.Parse(parts[0]) * 60 + int.Parse(parts[1]);
Console.WriteLine(seconds); // 605
You can also use TimeSpan.Parse in this case which is able to parse this format if you add a hour part in front of it. You can then use the TotalSeconds property to get your desired result:
double seconds = TimeSpan.Parse("00:" + s).TotalSeconds;
Console.WriteLine(seconds); // 605
#poke is close, but you asked for seconds, thus:
string s= "10:05";
double seconds = TimeSpan.Parse("00:" + s).TotalSeconds;
Returns 605.
There are many ways to do this. Here are just a couple. If you know that the format is always going to be mm:ss then you could use the TimeSpan class, the ParseExact method, and the TotalSeconds property. Here's an example of how you could do it.
TimeSpan ts = TimeSpan.ParseExact(mytime, "mm:ss", System.Globalization.CultureInfo.InvariantCulture);
double seconds = ts.TotalSeconds;
If you have a bunch of different formats that can show up you can use the ParseExact and provide multiple time formats. Here's an example that takes a few formats.
//HH -> 24 hour format always with 2 digits ("08" = 8 hours)
// H -> 24 hour format with as few digits as possible ("8" = 8 hours)
//mm -> minutes always with 2 digits ("08" = 8 minutes)
// m -> minutes with as few digits as possible ("8" = 8 minutes)
//ss -> seconds always with 2 digits ("08" = 8 seconds)
// s -> seconds with as few digits as possible ("8" = 8 seconds)
string[] formats = new string["HH:mm:ss", "H:mm:ss", "mm:ss", "m:ss", "ss", "s"];
TimeSpan ts = TimeSpan.ParseExact(mytime, formats, System.Globalization.CultureInfo.InvariantCulture);
double seconds = ts.TotalSeconds;
Here's a link to the MSDN documentation for the TimeSpan class. Check out the Methods and Properties for the TimeSpan class. Here's a link on formatting time strings.
The other way is to manually split the input string into the two parts and use the Convert class to convert each part into integers or doubles.
string[] timeparts = mytime.Split(':');
string minstr = timeparts[0];
string secstr = timeparts[1];
int mins = Convert.ToInt32(minstr);
int secs = Convert.ToInt32(secstr);
int seconds = mins * 60 + secs;
Here's the documentation for the Convert class.
I need to convert
20141013T155544.673-04/0
To a DateTime type.
Presently I am manually parsing the string out
//20130605T154727.683-04/0
//20130806T143808.018-04
//var a = new DateTime();
var year = segmentDate[0].ToString(CultureInfo.InvariantCulture) + segmentDate[1].ToString(CultureInfo.InvariantCulture) + segmentDate[2].ToString(CultureInfo.InvariantCulture) + segmentDate[3].ToString(CultureInfo.InvariantCulture);
var month = segmentDate[4].ToString(CultureInfo.InvariantCulture) + segmentDate[5].ToString(CultureInfo.InvariantCulture);
var day = segmentDate[6].ToString(CultureInfo.InvariantCulture) + segmentDate[7].ToString(CultureInfo.InvariantCulture);
//s[8] == "T";
var hours = segmentDate[9].ToString(CultureInfo.InvariantCulture) + segmentDate[10].ToString(CultureInfo.InvariantCulture);
var minutes = segmentDate[11].ToString(CultureInfo.InvariantCulture) + segmentDate[12].ToString(CultureInfo.InvariantCulture);
var seconds = segmentDate[13].ToString(CultureInfo.InvariantCulture) + segmentDate[14].ToString(CultureInfo.InvariantCulture);
string milliseconds = null;
if (segmentDate.Contains("."))
milliseconds = segmentDate.Split('.')[1].Split('-')[0];
if (milliseconds != null && milliseconds.Contains((" ")))
{
milliseconds = milliseconds.Split(' ')[0];
}
var offset = Convert.ToInt32(segmentDate.Split('-')[1].Split('/')[0]);
var a = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month),
Convert.ToInt32(day), Convert.ToInt32(hours), Convert.ToInt32(minutes),
Convert.ToInt32(seconds), Convert.ToInt32((milliseconds ?? "0"))).AddHours(offset);
But that is a bad idea - and I cannot believe that this format isnt specified somewhere (that I have been able to find).
Any help is appreciated.
Thank you!
Update
4 digit year
2 digit month
2 digit day
T - denotes start of the time portion
2 digit hour
2 digit minute
2 digit second
. - denotes start of MS
3 digit ms
TZ offset (-04)
/0 I believe is offset minutes
Update2
So I have been playing with TryParseExact and ParseExact - and cannot come up with a format string that will pull this into a DateTime/DateTimeOffset type.
I also consulted with the supplier of this value and they also have a manual process to parse it out, like I posted already.
I cannot accept that this is the only way to achieve the desired result, and as such, will continue to play with it.
But if anyone else has suggestions, they are welcome here.
Here's the closest I've gotten:
string s = "20141013T155544.673-04/0";
var dt = DateTime.ParseExact(s,"yyyyMMddTHHmmss.fffzz/0",CultureInfo.InvariantCulture);
If the /0 represents minutes (and can be 0 or 30 then you could do a little manipulation to convert that to a "standard" time zone indicator:
string s = "20141013T155544.673-04/30";
string s2 = s.Replace("/0",":00").Replace("/30",":30");
var dt = DateTime.ParseExact(s2,"yyyyMMddTHHmmss.fffzzz",CultureInfo.InvariantCulture);
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 am looking to use this plugin: http://keith-wood.name/countdown.html
but I need to use the TimeZone feature of it. So I was looking at the sample code
$('#sydneyCountdown').countdown({until: liftoffTime, timezone: +10});
so +10 is the TimeOffSet number. Now I need to make it so I can do a jquery get request and grab the TimeOffSet from the server(which gets the users time from the db and does TimeOffSet).
However it seems that C# TimeOffSet returns something like this "+02:00"(not this is just a random zone not the same as the one in the jquery example).
So it seems like all the C# TimeOffSet follow that format +/-xx:xx
So I don't understand why the jquery plugin is only 2 digts while the other one is 4 digits.
Can I know off safley the last 2 digits in the C# tomatch the plugin format?
Edit - would this work?
// working on how to get offsetTime will be posted soon.
string time = "-08:30";
string[] split = new string[] {":"};
string[] splited = time.Split(split, StringSplitOptions.RemoveEmptyEntries);
int hours = Convert.ToInt32(splited[0]);
int mins = Convert.ToInt32(splited[1]);
int totalMins = (hours * 60) + mins;
So just convert the hours to mins and then add the mins to it?
Edit - With offSetTime
var info = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
TimeSpan span = info.BaseUtcOffset;
string time = Convert.ToString(span);
string[] split = new string[] {":"};
string[] splited = time.Split(split, StringSplitOptions.RemoveEmptyEntries);
int hours = Convert.ToInt32(splited[0]);
int mins = Convert.ToInt32(splited[1]);
int totalMins = (hours * 60) + mins;
Problem though OffSet only gives me the number not the +/- sign. So I don't know how to get it.
Edit -
Never mind I it makes sense that they don't add the plus sign since I was just testing one that would have a "-" sign and it is shown.
The plugin says:
Cater for time zones with the timezone
setting, which is set to the target
time's offset from GMT, in either
hours or minutes.
So, I think based on the magnitude of the timezone value, it treats it either as hours or minutes. You should convert the <sign><hh>:<mm> format to into number of minutes, to account for timezones that are not hour-aligned. Something like:
var tz = "-08:30";
var tz_tokens = /([+\-])0?(\d+):(\d+)/.exec(tz);
var tz_minutes = (tz_tokens[1] + 1) * (tz_tokens[2] * 60 + tz_tokens[3]);
// ..., timezone: tz_minutes, ...