Q:
If i have two periods in the following format .ToString("H:m"); and i wanna to firstly subtract the end period from the first period ,then round the result .like the following example:
13:00 ---->First period.
13.45 ---->Last period.
the result 45 ----> round to 60
if the result = 75 for example then round to 120
Something like this
var t1 = TimeSpan.Parse("13:00").TotalMinutes;
var t2 = TimeSpan.Parse("13:45").TotalMinutes;
var round = (1 + ((int)(t2 - t1) / 60)) * 60; //Assuming t2 is always greater than t1
Hope this is what your looking for.
You can use datetime.parse to get two datetime objects for first and last period
then subtract them using lastperiod.subtract(firstperiod)
this will return u a timespan object
you can then round it as you want
Related
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.
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
}
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);
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;
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;
}