Converting a double to a time that makes sense - c#

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

Related

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.

How to return TimeSpan without formatting?

var timeSpan = new TimeSpan(10,130,10);
after the execution of above line, normally the value of timeSpan is formatted as 12:10:10
Is there any chance can I get value as 10:130:10 (i.e., without formatting)? I need it for a critical situation.
I don't believe there is a way you get 10:130:10 after you define your TimeSpan constructor. And there is no reason to keep them becuase 10 hours + 130 minutes + 10 seconds is equal to 12:10:10 as we all know. It is a time interval, not keeps time components separately.
From TimeSpan(Int32, Int32, Int32) constructor;
The specified hours, minutes, and seconds are converted to ticks, and
that value initializes this instance.
Let's look at how this contructor defined;
public TimeSpan(int hours, int minutes, int seconds)
{
_ticks = TimeToTicks(hours, minutes, seconds);
}
And this is how TimeToTicks methods implemented;
internal static long TimeToTicks(int hour, int minute, int second)
{
long totalSeconds = (long)hour * 3600 + (long)minute * 60 + (long)second;
if (totalSeconds > MaxSeconds || totalSeconds < MinSeconds)
throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("Overflow_TimeSpanTooLong"));
return totalSeconds * TicksPerSecond;
}
As you can see, this method doesn't keep constructor parameters (hours, minute or second). It just calculate totalseconds from hours * 3600 + minute * 60 + second value.
TimeSpan doesn't work like that. It represents an elapsed duration of time, not individual time components. See Soner's excellent answer for further details.
If you are looking to keep "10 hours, 130 minutes, 10 seconds" as separate information, then you should consider the ISO-8601 duration format. As a string, that value would look like "PT10H130M10S".
In .NET, you can use the Period type from the Noda Time library to work with these sort of values.
To create a single part period, you can take advantage of simple factory methods like Period.FromMonths(3). But to create a multi-part period, you will need to do one of the following approaches:
You can use a PeriodBuilder to build a period from individual variables:
PeriodBuilder builder = new PeriodBuilder();
builder.Hours = 10;
builder.Minutes = 130;
builder.Seconds = 10;
Period period = builder.Build();
string s = period.ToString();
Debug.WriteLine(s); // "PT10H130M10S"
You can parse a period from an ISO-8601 duration string, using a PeriodPattern. In particular, the RoundtripPattern shown below will retain the parts exactly as they were originally supplied:
string s = "PT10H130M10S";
PeriodPattern pattern = PeriodPattern.RoundtripPattern;
ParseResult<Period> result = pattern.Parse(s);
if (result.Success)
{
Period p = result.Value;
Debug.WriteLine(p.Hours); // 10
Debug.WriteLine(p.Minutes); // 130
Debug.WriteLine(p.Seconds); // 10
}

Calculate number of milliseconds until next occurence of a time

I feel like this is something really simple, but my Google Fu is letting me down as I keep finding difference calculations.
I have a time (e.g. 1800 hours) stored in a DateTime object. The date is null and immaterial. All I want to know is how many milliseconds until the NEXT occurrence of that time.
So, if I run the calculation at 0600 - it will return 12 hours (in ms). At 1750, it will return ten minutes (in ms) and at 1900 it will return 24 hours (in ms).
All the things I can find show me how to calculate differences, which doesn't work once you're past the time.
Here is what I tried, but fails once you're past the time and gives negative values:
DateTime nowTime = DateTime.Now;
TimeSpan difference = _shutdownTime.TimeOfDay - nowTime.TimeOfDay;
double result = difference.TotalMilliseconds;
You're already doing everything you should, except for one thing: handling negative results.
If the result is negative, it means the time you want to calculate the duration until has already passed, and then you want it to mean "tomorrow" instead, and get a positive value.
In this case, simply add 24 hours:
DateTime nowTime = DateTime.Now;
TimeSpan difference = _shutdownTime.TimeOfDay - nowTime.TimeOfDay;
double result = difference.TotalMilliseconds;
if (result < 0)
result += TimeSpan.FromHours(24).TotalMilliseconds;
The next thing to consider is this: If the time you want to calculate the duration until is 19:00 hours, and the current time is exactly 19:00 hours, do you want it to return 0 (zero) or 24 hours worth of time? Meaning, do you really want the next such occurrence?
If so, then change the above if-statement to use <=:
DateTime nowTime = DateTime.Now;
TimeSpan difference = _shutdownTime.TimeOfDay - nowTime.TimeOfDay;
double result = difference.TotalMilliseconds;
if (result <= 0)
result += TimeSpan.FromHours(24).TotalMilliseconds;
However, note that this will be prone to the usual problems with floating point values. If the current time is 18:59:59.9999999, do you still want it to return the current time (a minuscule portion of time) until 19:00 today, or do you want it to flip to tomorrow? If so, change the comparison to be slightly different:
DateTime nowTime = DateTime.Now;
TimeSpan difference = _shutdownTime.TimeOfDay - nowTime.TimeOfDay;
double result = difference.TotalMilliseconds;
if (result <= -0.0001)
result += TimeSpan.FromHours(24).TotalMilliseconds;
where -0.0001 is a value that corresponds to "the range of inaccuracy you're prepared to accept being tomorrow instead of today in terms of milliseconds".
When doing calculations like this it is important to take possible DST changes under consideration so that your results remain correct.
Suppose your operational parameters are:
var shutdownTime = TimeSpan.FromHours(18);
// just to illustrate, in Europe there is a DST change on 2013-10-27
// normally you 'd just use DateTime.Now here
var now = new DateTime(2013, 10, 26, 20, 00, 00);
// do your calculations in local time
var nextShutdown = now.Date + shutdownTime;
if (nextShutdown < now) {
nextShutdown = nextShutdown.AddDays(1);
}
// when you want to calculate time spans in absolute time
// (vs. wall clock time) always convert to UTC first
var remaining = nextShutdown.ToUniversalTime() - now.ToUniversalTime();
Console.WriteLine(remaining);
The answer to your question would now be remaining.TotalMilliseconds.

MMMMMMSS what kind of a time duration format is this?

i have a file which states duration for a particular event in format MMMMMMSS.Does any one know what kind of format is this for time duration and how to convert it into seconds.I'm using C# language
If the format is really M...MSS (supplied as an integer value), converting it to seconds is quite easy:
var seconds = (value / 100) * 60 + (value % 100);
Why does it work?
value / 100 removes the last two digits (integer division), thus returning MMMMMM, and
value % 100 returns the last two digits (modulo), i.e., SS.
The remainder of the formula is MMMMMM * 60 + SS, which should be pretty self-explanatory.
My guess based on the format is that it could hold a maximum value of 99999959, which would mean 999999 minutes and 59 seconds. But that is pure conjecture, and some sample data would help to bolster this idea. You may never know for certain though.
You should at least be able to determine whether the SS part ever exceeds 59 or not, which would be very important to know.
var input = "02345612";
int minutes = int.Parse(input.Substring(0, 6));
int seconds = int.Parse(input.Substring(6, 2));
int totalSeconds = minutes * 60 + seconds;

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