compare two dates time hours and minutes (not secs)? - c#

This is may be silly question. But I am missing logic here. I have to compare dates with date time with hours and minutes (not with seconds).
IF first field time is older then second field execute condition
right now I am doing if (Convert.ToDateTime(newItem["Modified"]) < Convert.ToDateTime(properties.ListItem["Modified"]))
example if("02/12/2015 11:58" < "02/12/2015 12:01") then execute condition.

You could create new DateTime objects with mostly the same values, but with seconds set to 0. Example:
DateTime date1WithoutSeconds = new DateTime(dt1.Year, dt1.Month, dt1.Day, dt1.Hour, dt1.Minute, 0);
DateTime date2WithoutSeconds = new DateTime(dt2.Year, dt2.Month, dt2.Day, dt2.Hour, dt2.Minute, 0);
bool b = date1WithoutSeconds < date2WithoutSeconds;

You could subtract the two dates, and if the TotalSeconds of the difference is less than 60 AND the minues are the same, then they are equal:
var first = Convert.ToDateTime(newItem["Modified"]);
var second = Convert.ToDateTime(properties.ListItem["Modified"]);
if (first.Subtract(second).TotalSeconds < 60 && first.Minute == second.Minute)
{
Console.WriteLine("They are equal");
}

You should use the DateTime.CompareTo method.
Grab and assign both dates as DateTime objects:
DateTime date = Convert.ToDateTime(newItem["Modified"]);
DateTime compareDate = Convert.ToDateTime(properties.ListItem["Modified"]);
You can now use the CompareTo method of the DateTime object to see if the instance is earlier, the same, or later than the other, returning -1, 0, and 1 respectively.
So, following your example: if("02/12/2015 11:58" < "02/12/2015 12:01"), first date being date and second being compareDate, the code:
date.CompareTo(compareDate);
will return -1, telling you the instance invoking the method is earlier than the object you are comparing it to.
Here is the MSDN.

One more way that should work.
DateTime date1 = Convert.ToDateTime(newItem["Modified"]);
DateTime date2 = Convert.ToDateTime(properties.ListItem["Modified"]));
if( date1.AddSeconds(-date1.Second) < date2.AddSeconds(-date2.Second) ) {
}
But, I would wonder...is it really that you need to ignore the seconds and "floor" the result so that 12:59:00 is the same as 12:59:59 but different than 12:58:59 even though there's only a second of difference...or do you need to know that it's greater than a minute of difference? If you really just want to make sure that it is a minute apart, use TimeSpan (date1 - date2).TotalSeconds > 60
I doubt this is likely, but if your DateTime is a string WITH milliseconds, then do:
if( date1.AddSeconds(-date1.Second).AddMilliseconds(-date1.Millisecond) <
date2.AddSeconds(-date2.Second).AddMilliseconds(-date2.Millisecond) )
{
}

First of all, the sample data you've mentioned in your question doesn't include seconds, so by default Convert.ToDateTime will assign '00' as seconds, so it would compare without the seconds.
But let's say that you do provide seconds in the actual data. You can use the following:
var date1 = Convert.ToDateTime(newItem["Modified"]);
var date2 = Convert.ToDateTime(properties.ListItem["Modified"]);
if (date1.AddSeconds(-date1.Second) < date2.AddSeconds(-date2.Second))

Related

If condition not working as expected c#

This is now bugging me , i have tried to fix it for the past hour but still no luck!
I hope some one could spot what i'm doing wrong . here is my code:
var maxDays = 30;
DateTime today = DateTime.Now; //todays date
DateTime lastAction = '2017-03-07 12:47:58.967';
double totalDays = (lastAction - today).TotalDays;
var days = Math.Round(totalDays);
if(days > maxDays)
{
//never hits this even though days is greater than max days ..i'm so confused
}
what am i doing wrong?
Duplicate problem as here:
C# Number of days between two dates problem
Timespan.TotalDays can be negative. So in your case it is almost guaranteed that lastAction - today will be a negative number, and so will always be less than 30.
If you only care about the absolute value of days, use Math.Abs otherwise re-arrange so that you are subtracting lastAction from today (today - lastAction).
Note that due to rounding, your condition will still not be triggered if there is less than 1 day difference.
Is it possible you are subtracting a larger value (today) from a small value (lastaction) which should result in a negative number making days negative?
That and you do need to do an explicit parse on the string to make it a date:
DateTime lastAction = DateTime.Parse("2017-03-07 12:47:58
.967");
Couple of things.
First you cant convert a string to DateTime like that. You should do something like this instead. DateTime lastAction = DateTime.Parse("2017-03-07 12:47:58.967");
Second, Just as #MikeS said, you are subtracting the lastAction from Today, which is resulting in a negative number (in this case its like -173). You should flip that statement. double totalDays = ( today - lastAction).TotalDays;
Your whole section should look something like this.
var maxDays = 30;
DateTime today = DateTime.Now; //todays date
DateTime lastAction = DateTime.Parse("2017-03-07 12:47:58.967");
double totalDays = ( today - lastAction).TotalDays;
var days = Math.Round(totalDays);
if (days > maxDays)
{
// now this is hit
}
Thanks for the help. I did something stupid .. I had
double totalDays = (lastAction - today).TotalDays; // returns -176
changed my code to:
double totalDays = (today - lastAction).TotalDays; //returns 176
Your first problem:
You didn't parse the string to DateTime.
DateTime lastAction = Convert.ToDateTime("2017-03-07 12:47:58.967");
Your second problem:
You were receiving a negative value, and checking if it's bigger.
var days = (Math.Round(totalDays)) * (-1);
Like this, it should work.

Comparing times without date?

I am having trouble comparing times.
From what I have researched it most likely is due to the time not having a date.
My code,
This gets a dateTime value from the database.
var getDateTime = sql.Staff_Time_TBLs.Where(p => p.Staff_No ==
SelectedEmployee.Key && p.Date_Data == day).Select(p => p.Time_Data_1).ToList();
DateTime dateTimeGet = Convert.ToDateTime(getDateTime);
dateTimeGet returns a value like this "2012/12/12 15:03:00.000"
I then declare variables to hold the time.
TimeSpan startCompare = TimeSpan.Parse("15:00");
TimeSpan endCompare = TimeSpan.Parse("21:00");
Then comparing the values Compare DateTime
if ((endCompare > dateTimeGet) && (startCompare < dateTimeGet))
{
//match found
}
I am getting a compile error,
operands cannot be given to to type timespan and datetime
How do I compare times in this situation?
Just edit your code like this:
if ((endCompare > dateTimeGet.TimeOfDay) && (startCompare < dateTimeGet.TimeOfDay))
{
//match found
}
You could create DateTime values instead of TimeSpan to compare the value, using the Date of your db time:
DateTime startCompare = dateTimeGet.Date.AddHours(15);
DateTime endCompare = dateTimeGet.Date.AddHours(21);
if ((endCompare > dateTimeGet) && (startCompare < dateTimeGet))
{
// match found
}
In the example you showed, actually would be enough to compare the Hour part of dateTimeGet:
if (dateTimeGet.Hour >= 15 && dateTimeGet.Hour <= 21)
// match found
Actually you are comparing time with date in endCompare > dateTimeGet so you are getting the error
operands cannot be given to to type timespan and datetime
To compare time-span you need to extract the time from date in dateTimeGet by simply using TimeOfDay.
if ((endCompare > dateTimeGet.TimeOfDay) && (startCompare < dateTimeGet.TimeOfDay))
{
//match found
}
This will convert the date into time. For more details about TimeOfDayclick here Hope this works fine for you.
The issue is that, as you rightly say, you are comparing dates to times
A time-span is a measurement of time measured in Hours, where as a date-time is a measurement of time measured in days
so 2012/12/12 15:03:00.000 is approximately 735248.625 days or 17645967 hours
which you are then comparing to a timespan of 15 hours
so you need to either add 735248 days to your time span or drop 735248 days form your Date
both can be easily done
If you call the time TimeOfDay property on the date it will ignore the days and just return 0.625 days as 15 hours
Which means your code would look like this
if ((endCompare > dateTimeGet.TimeOfDay ) && (startCompare < dateTimeGet.TimeOfDay))
OR
If you add the time span to the at midnight date it will create the correct date time for comparation
Which means your code would look like this
if ((dateTimeGet.Date + endCompare > dateTimeGet ) && (dateTimeGet.Date + startCompare < dateTimeGet.TimeOfDay))

Date comparison - How to check if 20 minutes have passed?

How to check if 20 minutes have passed from current date?
For example:
var start = DateTime.Now;
var oldDate = "08/10/2011 23:50:31";
if(start ??) {
//20 minutes were passed from start
}
what's the best way to do this?
Thanks :)
You should convert your start time to a UTC time, say 'start'.
You can now compare your start time to the current UTC time using:
DateTime.UtcNow > start.AddMinutes(20)
This approach means that you will get the correct answer around daylight savings time changes.
By adding time to the start time instead of subtracting and comparing the total time on a TimeSpan you have a more readable syntax AND you can handle more date difference cases, e.g. 1 month from the start, 2 weeks from the start, ...
var start = DateTime.Now;
var oldDate = DateTime.Parse("08/10/2011 23:50:31");
if ((start - oldDate).TotalMinutes >= 20)
{
//20 minutes were passed from start
}
var start = DateTime.Now;
var oldDate = DateTime.Parse("08/10/2011 23:50:31");
if(start.Subtract(oldDate) >= TimeSpan.FromMinutes(20))
{
//20 minutes were passed from start
}
Parse oldDate into a DateTime object (DateTime.Parse).
Subtract the parsed date from start. This will return a TimeSpan.
Inspect TotalMinutes.
I was able to accomplish this by using a JodaTime Library in my project. I came out with this code.
String datetime1 = "2012/08/24 05:22:34";
String datetime2 = "2012/08/24 05:23:28";
DateTimeFormatter format = DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss");
DateTime time1 = format.parseDateTime(datetime1);
DateTime time2 = format.parseDateTime(datetime2);
Minutes Interval = Minutes.minutesBetween(time1, time2);
Minutes minInterval = Minutes.minutes(20);
if(Interval.isGreaterThan(minInterval)){
return true;
}
else{
return false;
}
This will check if the Time Interval between datetime1 and datetime2 is GreaterThan 20 Minutes. Change the property to Seconds. It will be easier for you know. This will return false.
var end = DateTime.Parse(oldDate);
if (start.Hour == end.Hour && start.AddMinutes(20).Minute >= end.Minute)

C# Is it possible to convert DateTime format to integer or float?

I'm having some trouble here.
Did some research on Google but I can't seem to find what I'm looking for.
I'm trying to ask for two inputs (datetimes) in hh:mm format, subtract one for the other then return the result of that value in minutes.
The problem is that I want to return that value as an integer and I can't seem to find the right way to do it.
In C/C++ I wouldn't have this kind of issues...
Anyways, here's a snippet of what I'm talking about.
private int DuraçaoTreino(DateTime dtInicioTreino, DateTime dtFimTreino, int dtDuraçao)
{
Console.WriteLine("Introduza a hora de inicio (hh:mm): ");
dtInicioTreino = Convert.ToDateTime(Console.Read());
Console.WriteLine("Introduza a hora de fim (hh:mm): ");
dtFimTreino = Convert.ToDateTime(Console.Read());
dtDuraçao = (dtFimTreino - dtInicioTreino); // duração da sessão de treino
dtDuraçao = Convert.ToDecimal(Console.Read());
return dtDuraçao;
}
And that's pretty much it... I'm new to C# so if you see anything wrong please be kind.
Thanks in advance.
What you're talking about is a TimeSpan:
DateTime dtBegin = new DateTime(2011,5,1,22,0,0) ; // 10pm 1 May 2011
DateTime dtEnd = new DateTime(2011,5,1,23,0,0) ; // 11pm 1 May 2011
TimeSpan tmElapsed = dtEnd - dtBegin ; // tmElapsed is a TimeSpan with a value of 60 minutes
To return the minutes, do something like:
int elapsedTimeInMinutes = (int) Math.Round( tmElapsed.TotalMinutes , 0 ,MidpointRounding.ToEven ) ;
var timeInMinutes = new DateTime(2011, 12, 25).Subtract(new DateTime(2010, 1, 1)).TotalMinutes;
Instead of creating the DateTime objects using the constructor I used, you can use DateTime.Parse, or better still DateTime.ParseExact to convert the strings to date times. (I know I am only using date parts here but you choose only to use time parts if you wish)
Convert DateTime objects to TimeSpan's, substract and call TimeSpan.TotalMinutes (or smth like that - dont' have VS at hand):
DateTime dt1, dt2;
// Assign some dates, then:
TimeSpan ts = dt2 - dt1;
double minutes = ts.TotalMinutes;

Calculate time between 9:00 AM -- 6:00 PM

I'm having a string with 8:00 AM. Suppose I want to check that time 8:00 AM comes before 9:00 Am -- 6:00 PM.
How to check this or if time 11:00 AM comes in between time 9:00 AM -- 6:00 PM?
How to find it out in c#?
You can use the DateTime object, its static parse method, and comparison operators.
Something like the following:
newTime = DateTime.Parse("8:00 AM");
fixedTime = DateTime.Parse("11:00 AM");
if (newTime < fixedTime)
{
// do something
}
If needed, you can subtract one DateTime from another to get a TimeSpan - that is a duration.
String s = "8:00 AM";
DateTime dt = DateTime.Parse(s);
if (dt < DateTime.Parse("9:00 AM"))
{
Console.WriteLine("Before");
}
else if (dt <= DateTime.Parse("6:00 PM"))
{
Console.WriteLine("Between");
}
else
{
Console.WriteLine("After");
}
The general method would be to convert the time to a number that you can then use to compare.
So 8:00 AM would be simply 8, 6:00 PM would be 18, therefore 18 > 8 etc.
The function DateTime.Parse() can be used to turn strings into "DateTime" objects.
You have your start time: 9:00AM.
You have your end time: 6:00PM.
You therefore have your distance between the two:
6:00PM - 9:00AM.
That will give you a TimeSpan object.
Then you take your 'mystery time', and do:
X:XX - 9:00AM.
If the resulting timespan is > 0 AND the resulting timespan is < 6:00PM-9:00AM tiemspan, you're good.
Alternately, you can simply do
if (myTime > 9:00AM && myTime < 6:00PM)
DateTime beginDate = DateTime.Today.AddHours(9);
DateTime endDate = DateTime.Today.AddHours(18);
TimeSpan diff = endDate - beginDate;
Now diff contains difference between begin date and end date.
what about
int _dateTimeCompare = DateTime.Compare(DateTime1, DateTime2);
and then _dateTimeCompare < 1 = DateTime 1 is less than DateTime2, 0 = they're the same, > 0 = DateTime2 > DateTime1
So you can then do the comparisons.
A simple is _myDate between _date1 and _date2 would then be:
if (DateTime.Compare(_myDate, _date1) >= 0 && DateTime.Compare(_myDate, _date2) <= 0)
{
// we're between _date1 and _date2
}
kinda thing :)
I don't see the problem casting the strings to DateTime variables (as they should be) and then using the Compare method to perform the comparison.
Additionally, the DateTime structure implements operators such as >, <, >=, <= which simplify comparisons.
You can try to parse your string into a TimeSpan object using TimeSpan.Parse or TimeSpan.TeyParse.
If the parse succeeds, you'll have a TimeSpan object that can be compared to other timespan objects using the standard comparison operators. You can also carry out operations such as addition and substraction to calculate time between two timespans or to calculate a new time based on a time and duration.
Timespan is a very nice little class, please do not reinvent the wheel.
Update
As remarked by Cerebrus in the comment, TimeSpan is kind of weird in the sense that it can represent both a point in time and a duration. (The DateTime.TimeOfDay property is a Timespan even though it is a point in time).
It is perhaps a better idea to create DateTime objects with a default date part and use this as the basis of calculations. The intent of the code will be clearer.
Operations such as comparisons, additions and substractions are also available on DateTimes and yield DateTimes or TimeSpan where applicable.

Categories

Resources