How to combine integers in c# [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Im looking for a way to combine my integers together.
I got 3 integers i want to make one from them.
All the integers are holding a time currency wich looks a little like this:
var date = DateTime.Now;
int timeHours = date.Hour;
I got the Hours, Minutes and Seconds and want to combine so they would look like this:
Hour : Minutes : Seconds
How can i combine the integers together to do that.
Note: I've looked on the internet but i could not get the information i was looking for.
This is what i looked at:
Combine two integers to create a unique number
How to combine 2 integers in order to get 1?

Combining these integers will generate a string, not an another integer. You can easily format your DateTime with ToString() method like;
var str = DateTime.Now.ToString("H':'m':'s"); // eg: 11:0:2
If you wanna get your hour, minute and second part with leading zeros for single digits, you can use HH:mm:ss format instead.
var str = DateTime.Now.ToString("HH':'mm':'ss"); // eg: 11:00:02

DateTime.Now already contains all information you need, date and time. All you need to do is format this information

There're many ways to pack two (or many) integers into one based
on their ranges, e.g.
int i1 = 123;
int i2 = 456;
// two 32-bit integers into 64-bit one
long result = (((long) i1) << 32) | i2;
In your particular case
int hours = 5;
int minutes = 10;
int seconds = 59;
int combined = hours * 3600 + minutes * 60 + seconds;
reverse:
int combined = 12345;
int seconds = combined % 60;
int minutes = (combined / 60) % 60;
int hours = combined / 3600;

you can try the below code i think it's useful
var date = DateTime.Now;
var result = date.Hour + ":" + date.Minute + ":" + date.Second;
Console.WriteLine(result);

A simple way using the base 10 number system is to just
var number = hours * 10000 + minutes * 100 + seconds
this returns a number like 150936 for 15:09:36
To convert back:
seconds = number % 100
minutes = (number / 100) % 100
hours = number / 10000
Note that this is obviously not the most efficient approach, but simple

You should cast to string with format function for example:
string result = string.Format("{0:00}:{1:00}:{2:00}", timeHours, timeMinutes, timeSeconds);
Just to be complete:
format HH:mm:ss:
string result = string.Format("{0:00}:{1:00}:{2:00}", timeHours, timeMinutes, timeSeconds);
string result = DateTime.Now.ToString("HH:mm:ss");
format H:m:s:
string result = string.Format("{0}:{1}:{2}", timeHours, timeMinutes, timeSeconds);
string result = DateTime.Now.ToString("H:m:s");

Related

Sum of 3 numbers representing Hours in linq query or c#

I have column with spent hours values like (10.30,1.45 ...)
I want to sum those numbers to get the total spent hours.
Example:
Values 11.11,
0.50, 0.59
Total spent hours 11 and the sum of minutes
(11 + 50 + 59) = 120 minutes = 2 hour
So my final output should be 11 + 2 = 13.00 hour
but in my c# query I am getting 11.11 + 0.50 + 0.59 = 12.2 which is wrong as i considered it as hour format.
How can get the result 13.00 hours without splitting the numbers.
I Tried:
db.myTable.Where(t => t.is_deleted == false).Sum(t => t.time_spent)
which is giving me 12.2 but i want 13.00 as i considered it as time.
EDIT:
I used
List<string> hoursTemp1 = Model.tblName.Where(t => t.is_deleted == false).Select(p => p.time_spent.ToString()).ToList();
var total_effort_hr = new TimeSpan(hoursTemp1.Sum(x => TimeSpan.ParseExact(x, "h\\.mm", System.Globalization.CultureInfo.InvariantCulture).Ticks)).ToString(#"hh\:mm");
But now I am Getting OverflowException for Hour value Greater then 24 and minute value greater then 60
So can anyone please help me how to resolve this error and get proper result?
Any help will be apreciated.
var times = new string[] { "11.11", "0.50", "0.59" };
var totalTime = new TimeSpan(times.Sum(x => TimeSpan.ParseExact(x, "h\\.mm", CultureInfo.InvariantCulture).Ticks));
Console.WriteLine(totalTime); //13:00:00
public decimal GetHours(IEnumerable<decimal> args)
{
return args.Sum(x=> Math.Truncate(x) + (x-Math.Truncate(x))*100/60);
}
Or with one truncate:
public decimal GetHours(IEnumerable<decimal> args)
{
return args.Sum(x=> (5*x-2*Math.Truncate(x))/3);
}
But seriously, I will cutoff hand for such datetime handling. Almost every database has type that represents date, time or both. Why not to use them to avoid this kind of crap?

Add decimal number to Date - C#

How to convert a decimal number (e.g. 2.5) to year and month (2 years and 6 months) and add it to a given date? I tried DateTime.TryParse and it didn't work.
If you are using it for years then multiply the float you have by 12. 2.5 becomes 30months. Then use the addmonths function. If I enter 5 then it will add 60 months which is 5 years
Usually you could just add a TimeSpan or use one of the Add methods, like this:
decimal yearsToAdd = (decimal)2.5;
int years = (int)Math.Floor(yearsToAdd);
decimal months = yearsToAdd - years;
int actualMonths = (int) Math.Floor(months * 12); // or Ceiling or Round
DateTime x = DateTime.Now.AddYears(years).AddMonths(actualMonths);
The problem is, that when you decimal doesn't yield an exacat number of months, how would you know how long e.g. half a month is?
28.0 / 2, 29.0 / 2, 30.0 / 2 or 31.0 / 2?
Would you take the length of the month you started with or one of the possible two months you end up with?
If you init date is dt than
dt = dt.AddMonths((int)(2.5*12));
decimal x =(decimal)2.5;
int nbYear = Convert.ToInt16(x);
var y = x - Math.Truncate(x);
int nbMonth =Convert.ToInt16 (y*12);
// MessageBox .Show (string.Format (" {0} years and {1} months ",nbYear ,nbMonth ));
DateTime dat=DateTime .Now ; // or given date
DateTime dat2 = dat.AddYears(nbYear).AddMonths(nbMonth);
If month is your smallest unit then the solution is, as pointed by many, to multiply number by 12. A more accurate alternative would be to use ticks.
decimal years=3.14592M; // No idea where this came from.
long ticks = (long)(356.0M * (decimal)TimeSpan.TicksPerDay * years);
DateTime futureDate=DateTime.Today.AddTicks(ticks);
Note that solution will not compensate for leap years. It is not difficult to extend it - you need to calculate number of leap years in the period and use average instead of 356.0M to calculate ticks per year (i.e. avg. number of days per year * ticks per day).

Parse DateTime in format: 15:31:58:13943730921 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How do I parse the following time in C# ?
15:31:58:13943730921
What are the last 11 digits?
Something naive would be:
var time = "15:31:58:13943730921";
var str = time.Split(':');
var res = new TimeSpan(int.Parse(str[0]), int.Parse(str[1]), int.Parse(str[2])).Add(TimeSpan.FromTicks((long.Parse(str[3]) + 5000) / 10000));
Note that it won't work if the number of digits of the fractions of seconds change.
Ah... and it's a TimeSpan, not a DateTime probably :-)
The + 5000) / 10000 is to round to the nearest Tick.
A more complete solution that will handle any number of digits:
var time = "15:31:58:13943730921";
var str = time.Split(':');
// Used for the rounding
int carryover = 0;
if (str[3].Length < 7)
{
str[3] = str[3] + new string('0', 7 - str[3].Length);
}
else if (str[3].Length > 7)
{
char eight = str[3][7];
if (eight >= 5)
{
carryover = 1;
}
str[3] = str[3].Remove(7);
}
var res = new TimeSpan(int.Parse(str[0]), int.Parse(str[1]), int.Parse(str[2])).Add(TimeSpan.FromTicks(long.Parse(str[3]) + carryover));
Note that the TimeSpan constructor doesn't support a hour/minute/seconds + ticks, so we have to handle it in a different way (by using the .Add). Other solutions are clearly possible.
This is what I have done.
internal string GetTime(string line)
{
// ...
string tmp = time.Substring(0, 12);
time = DateTime.ParseExact(tmp, "HH:mm:ss:fff", CultureInfo.CurrentUICulture).Ticks.ToString();
return time;
}
If you want to round correctly to a whole number and ticks, with .NET 4.0 and later you can do:
string time = "15:31:58:13943730921";
var ts = TimeSpan.ParseExact(time.Remove(16), "h':'mm':'ss':'fffffff", null);
if (time[16] >= '5')
ts += new TimeSpan(1L); // add one tick for better rounding
Console.WriteLine(ts);
16 is the index in the string of the first character that we have to throw away.
May seem like an obvious answer.. But the question isn't too clear.
DataTime time = DateTime.Now;
string myTime = time.ToShortTimeString();
myTime = myTime.SubString(0, 7);

Converting a double to a time that makes sense

Basically I am setting a limit of hours a user can use. Now every time a button is press, whatever time that person accrued gets taken away from this total value.
However because a limit would be represented as say 156 hours, and the datetime representation of 5 minutes would be 00.05 the result would be 155.95, rather than 155.55 .
I work this out like so
string date2 = TotalMonthlyHours.ToString("HH.mm");
double date = double.Parse(date2);
RunningTotal = date + RunningTotal;
Total = limit - RunningTotal;
Any ideas?
I think you are trying to represent 5 minutes as 0.05. The way to do that is to first of all obtain the minutes as an integer. And then simply convert to double.
double floatmins = minutes/100.0;
And you convert in the other direction like this:
int minutes = (int) (floatmins*100.0);
However, I urge you not to go any further with this. You cannot expect to perform arithmetic on a quantity like that. What is the result of 2.20-1.50? You and I know it's 30 minutes, but the computer says 0.70 which is no use at all.
Store the hours using a true fractional representation. So 5 minutes is 5/60.0. Or store the total minutes in an integer. Or total seconds in an integer. Or a TimeSpan.
The key is that you can write your own helper routines to convert from a sane storage format to a value that is human readable. But you must store the raw data in a representation that will admit arithmetic operations.
I think I worked it out by doing something like this
string[] times = date.ToString().Split('.');
if (date != 0.0)
{
string minutesString = times[1];
string hoursString = times[0];
double minutes = Convert.ToDouble(minutesString);
double hours = Convert.ToDouble(hoursString);
// end of splitting
TimeSpan Limit = TimeSpan.FromHours(limit);
TimeSpan Hours = TimeSpan.FromHours((int)hours);
TimeSpan Minutes = TimeSpan.FromMinutes((int)minutes);
TimeSpan SubTotal = Hours + Minutes;
Time = Limit - SubTotal;
}
Edit: Glad you came up with the same as me,Just read your reply David, let's hope it works
I would convert it to minutes first than add as minutes to the date
var min = Convert.ToDouble(Convert.ToDecimal(textbox.Text) * 60);
DateTimePickerEnd.DbSelectedDate = e.NewDate.Value.AddMinutes(min);

Newbie C# Question about float/int/text type formatting

I'm a total C# newb with a light (first year CS) background in Python. I wrote a console program in Python for doing marathon pace running calculations and I'm trying to figure out the syntax for this in C# using Visual Studio 2010. Here's a chunk of what I've got so far:
string total_seconds = ((float.Parse(textBox_Hours.Text) * 60 * 60) + (float.Parse(textBox_Minutes.Text) * 60) + float.Parse(textBox_Seconds.Text)).ToString();
float secs_per_unit = ((float)(total_seconds) / (float)(textBox_Distance.Text));
float mins_per_unit = (secs_per_unit / 60);
string pace_mins = (int)mins_per_unit.ToString();
string pace_secs = (float.Parse(mins_per_unit) - int.Parse(mins_per_unit) * 60).ToString();
textBox_Final_Mins.Text = pace_mins;
textBox_Final_Secs.Text = pace_mins;
Imagine you have a running pace of 8 minutes and 30 seconds per mile. secs_per_unit would be 510, mins_per_unit would be 8.5. pace_mins would simply be 8 and pace_secs would be 30. In Python I'd just convert variables from a float to a string to get 8 instead of 8.5, for example; hopefully the rest of the code gives you an idea of what I've been doing.
Any input would be appreciated.
For float to string if you want to cut off the fraction
.ToString("F0")
It would be better if you rephrase your question.
Hours and minutes should only take integers as you're already taking seconds (doesn't make sense to have have 1.5 hours and 30 minutes instead of just 2 hours 0 minutes).
var numHours = Convert.ToInt32(textBox_Hours.Text);
var numMinutes = Convert.ToInt32(textBox_Minutes.Text);
var numSeconds = Convert.ToDouble(textBox_Seconds.Text);
var totalDistance = Convert.ToDouble(textBox_Distance.Text);
var totalSeconds = ((numHours)*60) + numMinutes)*60 + numSeconds;
var secsPerUnit = totalSeconds/totalDistance;
var minsPerUnit = secsPerUnit/60;
var paceMinsStr = Math.Floor(minsPerUnit).ToString();
var paceSeconds = minsPerUnit - Math.Floor(minsPerUnit);
var paceSecondsStr = (paceSeconds/ 100 * 60).ToString();
Written quickly, haven't tested it.. but something like this should work, at least with very minor tweaks/typo fixes.
Try this. Overall, store things as integers more, rather than storing as floats and converting to integers multiple times. And don't convert to a string until the last moment.
// I'm assuming that the text boxes aren't intended to hold a fraction,
// "8.5", for example. Therefore, use 'int' instead of 'float', and don't
// convert to a string at the end.
int total_seconds = int.Parse(textBox_Hours.Text) * 60 * 60 +
int.Parse(textBox_Minutes.Text) * 60 +
int.Parse(textBox_Seconds.Text);
// you missed a Parse here.
// Use two separate variables for seconds per unit:
// one for the total (510, in your example), one for just the seconds
// portion of the Minute:Second display (30).
int total_secs_per_unit = (int)(total_seconds / float.Parse(textBox_Distance.Text));
int mins_per_unit = total_secs_per_unit / 60;
int secs_per_unit = total_secs_per_unit % 60;
string pace_mins = mins_per_unit.ToString();
string pace_secs = secs_per_unit.ToString();
textBox_Final_Mins.Text = pace_mins;
textBox_Final_Secs.Text = pace_secs;
You could use the cast operators and conversion functions.
This would be a cast:
double d = 1.2;
int i = (int)d;
This would be a conversion:
string s = "1";
int i = Convert.ToInt32(s);

Categories