Getting minutes from two DateTimes on different dates - c#

I am comparing two DateTimes to see if there is 10 or fewer minutes between them. If I do DateTimeA - DateTimeB, and A is on 4/1/13 and B is on 4/3/13 I won't get the desired results.
I am only worried about minutes. So DateTimeA takes place at 8:00 am and DateTimeB takes place at 12:20 pm, I would want the result to be 260 minutes.

(DateTimeA - DateTimeB).TotalMinutes % 24*60
Get the total number of minutes modulo the number of minutes in a day. That way you'll get rid of the different-day problem.

You will need to use DateTime.TimeofDay() To get the actual time values and then do arithmatic on them.
or use DateTime.Minute DateTime.Hour DateTime.Second. Here is a full explanation on DateTime objects: http://msdn.microsoft.com/en-us/library/system.datetime.aspx

(A - B).TotalMinutes
A-B will yield a Timespan, for which the total minutes can then be produced.

Related

Timespan in milliseconds to minutes and seconds only

I have a Timespan that is always in milliseconds, but I need to show the date in minutes and seconds only so that it's always "mm:ss". Even if there are hours in the timespan, the output string should contain only minutes and seconds.
For example, if there is a timespan of 02:40:30, it should get converted to 160:30.
Is there a way to achieve this?
Reed's answer is ALMOST correct, but not quite. For example, if timespan is 00:01:59, Reed's solution outputs "2:59" due to rounding by the F0 numeric format. Here's the correct implementation:
string output = string.Format("{0}:{1:00}",
(int)timespan.TotalMinutes, // <== Note the casting to int.
timespan.Seconds);
In C# 6, you can use string interpolation to reduce code:
var output = $"{(int)timespan.TotalMinutes}:{timespan.Seconds:00}";
You can format this yourself using the standard numeric format strings:
string output = string.Format("{0}:{1}", (int)timespan.TotalMinutes, timespan.Seconds);
I do it this way
timespan.ToString("mm\\:ss");
That is a pretty basic math problem.
Divide by 1000 to get total number of seconds.
Divide by 60 to get number of minutes.
Total seconds - (minutes * 60) = remaining seconds.

SQLIte SUM datetimes

I have a database with rows, with time values. I want a SUM of that time values (generaly, the format are %H:%M).
I used SUM value like that:
SELECT SUM(n_hores) FROM table;
But only I get 0.0.
How I can do that ?
Thanks
Time values in hh:mm format are strings, and strings cannot be summed meaningfully.
You should convert these time values into a number (strftime(%s) returns the number of seconds since 1970-01-01, so you have to subtract the offset from the start of the day to get the number of seconds corresponding to your time value):
SELECT sum(strftime('%s', MyTime) - strftime('%s', '00:00')) FROM MyTable
You can also convert this number of seconds back into a time string (time() returns it in hh:mm:ss format):
SELECT time(sum(strftime('%s', MyTime) - strftime('%s', '00:00'))) FROM MyTable
You're probably better off subtracting the two dates by getting the "number of milliseconds since the last epoch aka (modern epoch)." There should be a function, in SQLite, that returns the number of milliseconds since the last epoch. Once you've found this, the solution should be a simple subtraction and conversion to seconds, minutes and/or hours.

Get Hours and Minutes from Datetime

Out Time :
2013-03-08 15:00:00.000
In Time :
2013-03-08 11:21:03.290
I need to get Hours and Minutes separately for same date from above, when (Out Time - In Time).
How can I do that ?
I think you probably just want:
TimeSpan difference = outTime - inTime;
int hours = (int) difference.TotalHours;
int minutes = difference.Minutes;
Note that Minutes will give you "just the minutes (never more than 59)" whereas TotalHours (truncated towards zero) will give you "the total number of hours" which might be more than 23 if the times are more than a day apart.
You should also consider what you want to do if the values are negative - either consider it, or explicitly rule it out by validating against it.
The Subtract method on the DateTime class will allow you subtract that date from the other date.
It will give you a TimeSpan which will be the difference.
I'll leave it to you to work out the actual code.
http://msdn.microsoft.com/en-GB/library/8ysw4sby.aspx
You can use Hours property and Minutes
link : http://msdn.microsoft.com/en-us/library/system.datetime.hour.aspx

Converting a value of more than 59 (seconds) effectively into a DateTime

I am getting 'time played' values which come as an integer in the amount of seconds.
Providing there is less than 60 seconds to be added, it's ofcourse easily done.
However, a lot of the values are more than 59 seconds and therefore cannot easily be converted into a DateTime.
An example of a value would be: 159, which means that the 'time played' is 2 minutes and 39 seconds.
Thanks in advance.
A "number of seconds" shouldn't be stored in a DateTime in the first place. You should use TimeSpan, which makes it easy:
TimeSpan ts = TimeSpan.FromSeconds(159);
You can add a duration of time to any DateTime, of course, but that's a different matter.
(You might also want to look into my Noda Time library if you're doing any significant amount of work with dates and times... the BCL provision is somewhat underwhelming.)
I think you want to use a TimeSpan not a DateTime. Specifically TimeSpan.FromSeconds().
See: http://msdn.microsoft.com/en-us/library/system.timespan.fromseconds.aspx
What you want is a TimeSpan structure.

How to round a DateTime in MySQL?

I want to discretize the DateTime with the resolution of 5 minutes. I did it in C#, but how to convert the following code to MySQL?
DateTime Floor(DateTime dateTime, TimeSpan resolution)
{
return new DateTime
(
timeSpan.Ticks *
(long) Math.Floor
(
((double)dateTime.Ticks) /
((double)resolution.Ticks)
)
);
}
It's a little nasty when you do it with datetime data types; a nice candidate for a stored function.
DATE_SUB(DATE_SUB(time, INTERVAL MOD(MINUTE(time),5) MINUTE ),
INTERVAL SECOND(time) SECOND)
It's easier when you use UNIXTIME timestamps but that's limited to a 1970 - 2038 date range.
FROM_UNIXTIME(UNIX_TIMESTAMP(time) - MOD(UNIX_TIMESTAMP(time),300))
Good luck.
from_unixtime(floor(unix_timestamp('2006-10-10 14:26:01')/(60*5))*(60*5))
+---------------------------------------------------------------------------+
| from_unixtime(floor(unix_timestamp('2006-10-10 14:26:01')/(60*5))*(60*5)) |
+---------------------------------------------------------------------------+
| 2006-10-10 14:25:00 |
+---------------------------------------------------------------------------+
1 row in set (0.00 sec)
you can replace the two 5s with other values
You can look here. This example is a general case for rounding to the nearest X minutes, and is written in T-SQL, but the logic and the majority of the functions will be the same in both cases.
Another alternative:
to get the nearest hour:
TIMESTAMPADD(MINUTE,
ROUND(TIMESTAMPDIFF(MINUTE,CURDATE(),timestamp_column_name)/60)*60,
CURDATE())
Instead of CURDATE() you can use an arbitrary date, for example '2000-01-01'
Not sure if there could be problems using CURDATE() if the system date changes between the two calls to the function, don't know if Mysql would call both at the same time.
changing 60 by 15 would get the nearest 15 minutes interval, using SECOND you can get the nearest desired second interval, etc.
To get the previous hour use TRUNCATE() or FLOOR() instead of ROUND().
Hope this helps.
Have you had a look at the CAST functionality in MySQL?
MySQL Cast
Cast Functions and Operators
Here is another variation based on a solution from this thread.
SELECT DATE_ADD(
DATE_FORMAT(time, "%Y-%m-%d %H:00:00"),
INTERVAL FLOOR(MINUTE(time)/5)*5 MINUTE
);
This solution, unlike ones that use FROM_UNIXTIME, will give the expected value for datetimes that fall within daylight saving time (DST) transitions. (Compare for example 2012-11-03 2:14:00)
Edit - After some quick benchmarking, however, Ollie's first solution appears to perform faster than this. But I still recommend against the FROM_UNIXTIME method.

Categories