TimeSpan.TotalMinutes without seconds - c#

I am using the code
var minutesPassed = (DateTime.UtcNow - conversionsList.Last().DateStamp).TotalMinutes;
to calculate how much minutes passed between two dates. The result which I get looks like
254.54445556
I get minutes and seconds. How to get result which would contain only minutes like this
254
?

Just explicitly convert the result to int:
var minutesPassed = (int)(DateTime.UtcNow - conversionsList.Last().DateStamp).TotalMinutes;

Use Math.Floor() to convert 254.xxxx to 254:
var minutesPassed = Math.Floor((DateTime.UtcNow - conversionsList.Last().DateStamp).TotalMinutes);

You can just get the int part
int minutes = (int) (DateTime.UtcNow - conversionsList.Last().DateStamp).TotalMinutes;
this will get you the int part of the value.
EDIT: as far as rounding of value is considered. That is not true. Consider the following:
double d = 254.99999999999d;
int test = (int)d;
Here test will hold 254, not 255
The only problem with the explicit cast is OverFlowException

Related

DateTime difference in ticks does not match

I have the following code:
var a = (DateTime.Now.Subtract(DateTime.Now.AddTicks(8))).Ticks;
var b = (DateTime.Now - DateTime.Now.AddTicks(8)).Ticks;
When I check the values I see that:
a = -78
b = -20
How come? Shouldn't both be -8?
You are depending on the system to do everything at the same time, which it cannot. Each time you get DateTime.Now, it has a different value.
A quick experiment reveals that capturing the value of DateTime.Now in the beginning, and then performing operations on that:
var d = DateTime.Now;
var a = (d.Subtract(d.AddTicks(8))).Ticks;
var b = (d - d.AddTicks(8)).Ticks;
Yields the result you were expecting. a and b have the same value, -8.
Those lines of code take time to execute. It's never good to use Now more than once in single method or operation. Or Today, for that matter.

How to get the total hours with different dates in C#

This is my problem now, i want to get the total hours and mins of work.
example from jan. 11 2017 22:00 to Jan. 12 2017 7:00.
so far i have it only work when the end date is not change
DateTime pin = today, pout = DateTime.Parse(empTime);
TimeSpan spanMe = pout.Subtract(pin);
spanMe.Hours
spanMe.Minutes
it gives me negative numbers.
it gives me negative numbers.
That is expected if you subtract a larger item from a smaller item (ie. subtracting a more recent time from an older time). If you always want to see the difference as a positive number and do not want to take into account which is larger then wrap the result of the properties (like .Hours) in Math.Abs (absolute value).
var hours = System.Math.Abs(spanMe.Hours);
var minutes = System.Math.Abs(spanMe.Minutes);
Also as pointed out by #stuartd there is a difference between Hours/Minutes and TotalHours/TotalMinutes. Make sure you are using the correct one for your needs.
It should work :
DateTime pin = DateTime.Parse("jan 11 2017 22:00");
DateTime pout = DateTime.Parse("Jan 12 2017 7:00");
TimeSpan spanMe = pout.Subtract(pin);
Console.WriteLine("Hours : {0}, Minutes : {1}", spanMe.Hours, spanMe.Minutes);
Console.ReadLine();
if you know what is the latest date, you need arrange it accordingly. If not, you can not multiply by -1:
double GetHouers(DateTime one, DateTime another)
{
var diff = (one - another).TotalHours;
return diff > 0 ? diff : diff * -1;
}
You can subtract one DateTime Object from another, and then use .TotalHours property of the DateTime class to get the number of hours. It will give you a double value representing the total hours.
DateTime pin = today, pout = DateTime.Parse(empTime);
double hours = (pout - pin).TotalHours;
DateTime pin = today, pout = DateTime.Parse(empTime);
TimeSpan spanMe = pin.Subtract(pout);
var hours = spanMe.TotalHours;
var minutes = spanMe.TotalMinutes;
You want to use TotalHours and TotalMinutes as these will handle fractions thereof, versus Hours and Minutes which return only whole values. You also need to swap the order of your operands as above for the subtraction step.

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);

C# format a double with ToString, and dispay zero value

I'm trying to find the best way to display a double in C# as follows:
7.345 should display as "73"
100.0 should display as "100"
0.234 shoud display as "02"
The input is a value between 0.00 and 10.00. I need to convert it to a filename. E.g. in case of a value of 5.4234, I should display "img54.jpg".
The problem is that I can't figure out how to display zero values in ToString() of doubles.
I tried this:
(10 * 7.345).ToString("##.") => correct
(10 * 10.00).ToString("##.") => correct
(10 * 0.000).ToString("##.") => FAIL, doesn't display anything.
(10 * 0.000).ToString("D2") => FAIL, D is not allowed in doubles
I can of course do some sophisticated string building, but if it's possible to use ToString, that would be much better of course.
Anyone an idea?
What do you want 0.00 to display as? "00"?
In that case you can try with format ToString("00.") instead.
Can you simply check if the double is 0? and If it is, set img00.jpg to your filename. That seems a lot easier than reworking your algorithm.
Why don't you convert it to an int?
int result = (int)(input * 10.00);
return result.ToString();
You could just convert to int before formatting like this:
((int)(10 * 7.345)).ToString("D2")
If you always have the input number of this format: #.###
You can multiply it by 1000 and divided by 100 and cast the result to an integer.
7.345 * 1000 = 7345 / 100 = 73.45 => Convert.ToInt32 => 73
0.000 * 1000 = 0 / 100 = 0 => Convert.ToInt32 = 0
Or you can multiply by 10 and convert to Integer.
return ((int)(input * 10.00)).ToString().SubString(0, 2);
double val = 7.345;
string result = val.ToString("0.#").Replace(".","");

Convert DateTime.Now to Seconds

I am trying to write a function that will convert a DateTime.Now instance to the number of seconds it represents so that I can compare that to another DateTime instance. Here is what I currently have:
public static int convertDateTimeToSeconds(DateTime dateTimeToConvert)
{
int secsInAMin = 60;
int secsInAnHour = 60 * secsInAMin;
int secsInADay = 24 * secsInAnHour;
double secsInAYear = (int)365.25 * secsInADay;
int totalSeconds = (int)(dateTimeToConvert.Year * secsInAYear) +
(dateTimeToConvert.DayOfYear * secsInADay) +
(dateTimeToConvert.Hour * secsInAnHour) +
(dateTimeToConvert.Minute * secsInAMin) +
dateTimeToConvert.Second;
return totalSeconds;
}
I realize that I am truncating the calculation for seconds in a year, but I don't need my calculation to be precise. I'm really looking to know if the method that I am using to calculate seconds is correct.
Does anyone have anything that could better compute seconds given from a DateTime object?
Also, Should the return type be int64 if I am coding in C# if I am going to calculate all the seconds since 0 AD?
The DateTime type supports comparison operators:
if (dateTimeA > dateTimeB)
{
...
This also works for DateTime values returned by DateTime.AddSeconds:
if (dateTimeA.AddSeconds(42) > dateTimeB)
{
...
If you really want the number of seconds that elapsed since 01/01/0001 00:00:00, you can calculate the difference between the two DateTime values. The resulting TimeSpan value has a TotalSeconds property:
double result = DateTime.Now.Subtract(DateTime.MinValue).TotalSeconds;
It really doesn't make sense to convert a DateTime object to seconds. Seconds only make sense if you are dealing with a length of time (TimeSpan). Should you want to compare two dates to get the number of seconds between them:
TimeSpan diff = DateTime.Now - PreviousDateTime;
double seconds = diff.TotalSeconds;
If the purpose is finding the number of seconds between two dates, you'd be much better off using the TimeSpan object.
TimeSpan span = date2 - date1;
double seconds = span.TotalSeconds;
See suggestion from thread below:
How do I convert ticks to minutes?
TimeSpan.FromTicks(DateTime.Now.Ticks).TotalSeconds;
Assuming you really need to get at the seconds for the datetime object, you could directly get the "Ticks" property from it. These aren't in seconds but you can easily divide by the proper factor to convert the Ticks to seconds.
See: http://msdn.microsoft.com/en-us/library/system.datetime.ticks.aspx
So, something like:
DateTime.Now.Ticks/TimeSpan.TicksPerSecond
If you want to compare 2 DateTime object, why just not use the provided operators?
http://msdn.microsoft.com/en-us/library/aa326723%28v=VS.71%29.aspx
DateTime a, b;
if (a > b) //a is after b
I would use the TimeSpan class to get the exact difference between two DateTime instances. Here is an example:
DateTime dt1 = DateTime.Now;
DateTime dt2 = new DateTime(2003,4,15);
TimeSpan ts = dt1.Subtract(dt2);
Once the TimeSpan value (ts, in the code snippet above) is available, you can examine its values to correctly convert the TimeSpan to a given number of seconds.
Using a TimeSpan to get the elapsed time between two DateTimes is probably the best way to go but if you really want to get the number of seconds for a given DateTime you could do something like the following:
DateTime dateTimeToConvert = DateTime.Now;
TimeSpan tsElapsed = dateTimeToConvert - DateTime.MinValue;
return tsElapsed.TotalSeconds;
Note that tsElapsed.TotalSeconds is a Double, not an Int.
Do note that the goal is to get the number of seconds since DateTime.MinVal (the first day of the calendar). I say this, because I see all of these answers for "you do time comparisons like this... add in the object, multiply by that object and do cross-calculus on them, divide by the quotient of the summed result, and Boom! not what you asked."
There's a really simple answer here. Ticks are 100-nanosecond increments. DateTime object.Ticks is the number of ticks that have occurred since 1/1/0001. Ie, year zero. There are 10 million nanoseconds in a second. so...
public static long convertDateTimeToSeconds(DateTime dateTimeToConvert) {
// According to Wikipedia, there are 10,000,000 ticks in a second, and Now.Ticks is the span since 1/1/0001.
long NumSeconds= dateTimeToConvert.Ticks / 10000000;
return NumSeconds;
}

Categories