Difference between two string time and now - c#

I have a string like that 03223311 (hhmmssff). I'm going to compare it with DateTime.Now and see if the difference between these to values is lower than 200 miliseconds.
xdate="03223311";
if(Math.Abs(Convert.ToInt32(xdate) - Convert.ToInt32(DateTime.Now.ToString("hhmmssff")))<200)
I tried to run the line above in a timer with interval of 1 but I can not reach to that condition even if I change xdate to current time... . Do you know how to solve the problem or even a better approach?

string input = "03223311";
var diff = DateTime.Now.TimeOfDay.Subtract(
TimeSpan.ParseExact(input, "hhmmssff", null)
).TotalMinutes; //or any other value like TotalMilliseconds

I would first convert the string into a DateTime so that you can compare apples to apples and utilized the features of the DateTime object. Once you have two DateTime objects, you can subtract them to get a TimeSpan. TimeSpan will have a TotalMilliseconds property that you can compare to your 200 constant.
var xdateValue = DateTime.ParseExact(xdate, "hhmmssff", CultureInfo.InvariantCulture);
var difference = DateTime.Now - xdateValue;
if (difference.TotalMilliseconds < 200) ...

if (((DatetTime.Now - DateTime.ParseExact("03223311 ", "hhmmssff", CultureInfo.InvariantCulture))).Milliseconds > 200)
{
}

Related

Finding if the two DateTime is within a week

I wanted to find if two DateTime are within a week.
One of them is the current system Datetime, which I got it by using:
DateTime CurrentDateTime = new DateTime();
CurrentDateTime = DateTime.Now;
The other DateTime will just be a selected date. Assuming it is stored in a variable called : ExportDate.
So, I can find the difference between them by doing
ExportDate.Subtract(CurrentDateTime)
But I cannot change this value into a int for comparing...
So how should I compare this to DateTime to see if this two dates are greater then 0Days, and less then 7Days.
Subtracting two datetimes gives you a TimeSpan. This class comes with a property called TotalDays.
Gets the value of the current TimeSpan structure expressed in whole and fractional days.
Src: https://msdn.microsoft.com/en-Us/library/system.timespan(v=vs.110).aspx
You can use to count the number of days I guess.
Regards,
Seb
Try to compare the TotalDays of the resulting TimeSpan. Depending on which is later, the result must be between -7 and 7. Use Math.Abs to avoid comparing the value against both bounds:
bool isWithinWeek = Math.Abs(ExportDate - CurrentDate).TotalDays) < 7
If the time of day is irrelevant, compare only the dates:
bool isWithinWeek = Math.Abs(ExportDate.Date - CurrentDate.Date).TotalDays) < 7
You can use
(ExportDate - CurrentDateTime).TotalDays <= 7
You can simply use the DayOfYear property of DateTime to get the day in the year and then check if the difference is less than 7 or not. You can try:
bool isWithinAWeek = Math.Abs(currentDateTime.DayOfYear-exportDate.DayOfYear)>7?false:true;

Best way to Compare DateTime to trigger code

What is the best way to compare two DateTime in a specific format and trigger code if DateTime has passed.
My DateTime is formatted as 4/26/2017 10:00:00 AM
DateTime currentDateTime = DateTime.Now;
DateTime eventDateTime = DateTime.Parse("4/26/2017 10:00:00 AM");
int result = DateTime.Compare(currentDateTime, eventDateTime);
if (result < 0)
Response.Write( "is earlier than Do Nothing");
else if (result == 0)
Response.Write("is the same time as: Do Nothing");
else
Response.Write("Time is greater, Trigger Action ");
Is the above code fine for comparison or we can improve it.
For my opinion, the method you suggested is the most efficiant and accepted way to compare 2 DateTime variables in C#, considering you need to take action if the 2 dates are also equal.
Side note:
If you only needed to compare the 2 DateTime without the equal condition, you could just write:
if (currentDateTime < eventDateTime)
Response.Write("is earlier than Do Nothing");
else
Response.Write("Time is greater, Trigger Action");
which is a bit cleaner and more efficiant.
To compare Dates, your method is efficient one because according to MSDN
The CompareTo method compares the Ticks property of the current instance and value but ignores their Kind property. Before comparing DateTime objects, make sure that the objects represent times in the same time zone.
So as it does compare Ticks of two instances of DateTime, so it is the efficient method for comparison.
As a side note, if you want to find interval between DateTime Instances then you can use DateTime.Subtraction it will give TimeSpan of both DateTime instances. So you can find total difference in their minutes, hours, days, seconds, milliseconds by using TimeSpan properties.
DateTime date1 = new DateTime(2010, 1, 1, 8, 0, 15);
DateTime dateNow = DateTime.Now;
TimeSpan interval = dateNow.Subtract(date1);
double totalHours= interval.TotalHours;
double totalMinutes = interval.TotalMinutes;
double totalSeconds= interval.TotalSeconds;
double totalMilliseconds= interval.TotalMilliseconds;
You can use nested if else statement as below:
if (currentDateTime < eventDateTime)
Response.Write("is earlier than Do Nothing");
else if(currentDateTime > eventDateTime)
Response.Write("time is greater, Trigger Action");
else
Response.Write("is the same time as: Do Nothing");

Exact c# result of sql datediff

I'm trying to get the number of days (calculated byu datediff) in sql and the number of days in c# (calculated by DateTime.now.Substract) to be the same, but they return different results....
//returns 0
int reso = DateTime.Now.Subtract(expirationDate).Days;
vs
//returns 1
dateDiff(dd,getDate(),ExpirationDate)
In both cases, ExpirationDate is '10/1/2011 00:00:00', and the code and the DB are sitting on the same server. I want the return int to be the same. I suspect I'm missing something stupid... ideas??
dateDiff(dd,getDate(),ExpirationDate) Is doing a days comparison. DateTime.Now.Subtract(expirationDate).Days is doing a date and time
For example
SELECT dateDiff(dd,'10/1/2011 23:59:00' , '10/2/2011') returns one day even when only one minute apart.
If you want the same in C# you need to remove the time component
e.g.
DateTime dt1 = new DateTime(2011,10,1, 23,59,0);
DateTime dt2 = new DateTime(2011,10,2, 0,0,0);
Console.WriteLine((int) dt2.Subtract(dt1.Subtract(dt1.TimeOfDay)));
So in your case it would be something like
DateTime CurrentDate = DateTime.Now;
int reso = CurrentDate.Subtract(CurrentDate.TimeOfDay).Subtract(DateTime.expirationDate).Days;
I haven't tested it but I would not do
DateTime.Now.Subtract(DateTime.Now.Subtract.TimeOfDay)
Because the second call to Now wouldn't be guaranteeing to be the same as first call to Now
In any case Stealth Rabbi's answer seems more elegant anyway since you're looking for a TimeSpan not a DateTime
10/1/2011 is less than 1 day away from DateTime.Now. Since you're getting back a TimeSpan and then applying Days to it, you're getting back a TimeSpan that is < 1 day. So it'll return 0 Days.
Instead, just use the Date component of those DateTimes and it'll correctly report the number of days apart - like this:
DateTime now = DateTime.Now;
DateTime tomorrow = new DateTime(2011, 10, 1);
var val = (tomorrow.Date - now.Date).Days;
This will yield you 1 day.
I'm assuming you want the number of Total days, not the number of days from the largest previous unit. You'd want to use the TotalDays property. Also, you may find it easier to use the minus operator to do a subtraction
DateTime d1 = DateTime.Now;
DateTime d2 = new DateTime(2009, 1, 2);
TimeSpan difference = d1 - d2;
Console.WriteLine(difference.TotalDays); // Outputs (today):1001.46817997424

How can I increment a date?

I have two dates as duedate as 03/03/2011 and returndate as 03/09/2011. I want to find the fine in double when I subtract duedate from returndate.How can duedate be incremented?
Following code might help you:
var dueDate = new DateTime(2011, 3, 3);
//if you want to increment six days
var dueDatePlus6Days = dueDate.AddDays(6);
//if you want to increment six months
var dueDatePlus6Months = dueDate.AddMonths(6);
var daysDiff1 = (dueDatePlus6Days - dueDate).TotalDays; //gives 6
var daysDiff2 = (dueDatePlus6Months - dueDate).TotalDays; //gives 184
The logical solution would seem to be the AddDays method, as in the other answers.
However, I try (in general) never to use floating point (i.e. a double) when working with monetary or date values.
DateTime contains a time component and AddDays takes a double as argument (fractional part becomes time), so I tend to avoid use of that method.
Instead, I use
dueDatePlusOne = dueDate.AddTicks(TimeSpan.TicksPerDay);
This should result in slightly faster execution too. Not that it still matters much on today's hardware, but I started out coding for microprocessors with a <1 MHz clock speed and old PDP-8's and -11's and stuff like that back in the 1970's, and some habits never die ;)
Assuming returnDate, dueDate are DateTime objects:
double extraDays = (returnDate - dueDate).TotalDays;
May this can help you
DateTime dt_duedate = DateTime.Now;
DateTime dt_returndate = DateTime.Now.AddDays(2);
System.TimeSpan diffResult = dt_returndate.Subtract(dt_duedate);

Add or Sum of hours like 13:30+00:00:20=13:30:20 but how?

I want to add seconds (00:00:02) or minutes (00:00:20) on datetime value (may be stored string type) but how? Examples:
13:30+02:02:02= 15:32:02 ,
13:30+00:00:01= 13:30:01 ,
13:30+00:01:00=13:31:00 or 13:30 (not important)
Can you help me? I need your cool algorithm :) Thanks again...
myDateTimeVariable.Add(new TimeSpan(2,2,2));
If you choose to use the TimeSpan, be aware about the Days part:
TimeSpan t1 = TimeSpan.Parse("23:30");
TimeSpan t2 = TimeSpan.Parse("00:40:00");
TimeSpan t3 = t1.Add(t2);
Console.WriteLine(t3); // 1.00:10:00
With DateTime:
DateTime d1 = DateTime.Parse("23:30");
DateTime d2 = DateTime.Parse("00:40:00");
DateTime d3 = d1.Add(d2.TimeOfDay);
Console.WriteLine(d3.TimeOfDay); // 00:10:00
Adding two datetimes from strings:
var result = DateTime.Parse(firstDate) + DateTime.Parse(secondDate);
Adding a string time to a datetime:
var result = existingDateTime.Add(TimeSpan.Parse(stringTime);
Adding time as in your example:
var result = TimeSpan.Parse("12:30:22") + TimeSpan.Parse("11:20:22");
Finally, your example as dates (not tested!):
var result = DateTime.Parse("12:30:22") + DateTime.Parse("11:20:22");
Note that this is sloppy coding, but you get the idea. You need to verify somehow that the string is actually parseable.
Not really sure what you're after, but can you not just use the built in functions to C#'s DateTime object?
DateTime myDate = DateTime.Now;
myDate = myDate.AddHours(1);
myDate = myDate.AddMinutes(30);
myDate = myDate.AddSeconds(45);
The problem is more abstract. As already mentioned, in .NET there are two types - DateTime and TimeSpan. The DateTime type represents a specific point in time. It's not an interval of time. It's a specific location in all time since the birth of the Universe. Even if you set the year/month/day components to 0, it will still represent some absolute point in time. Not a length of time.
The TimeSpan on the other hand represents some interval. 1 minute, 2 days, whatever. It's not specified WHEN, just HOW LONG.
So if you were to subtract two DateTime objects you would get a TimeSpan object that specifies how much time there is between them. And if you add a TimeSpan to a DateTime you get another DateTime. But you can't add a DateTime to another DateTime - that would make no sense.
It sounds to me like you should be working with TimeSpans all the time, because you are dealing with lengths of time, not absolute points in time. If you get these lengths from your source as a DateTime then that's actually not correct, and you should convert them to TimeSpans somehow. The parsing method is one way that has been suggested, but you might also try to subtract zero DateTime from it. That might be faster and more culture-independant.
use the TimeSpan structure. you can add TimeSpans together, or you can add a TimeSpan to a DateTime to produce a new DateTime.
You should have a look at TimeSpan.Parse. This converts a string to a TimeSpan object. That way you can do stuff like
TimeSpan a = TimeSpan.Parse(timeStringA)+TimeSpan.Parse(TimeStringB);
To split a string like "00:00:20+00:01:00" look at string.split
stringA = timeSting.split('+')[0];
stringb = timeSting.split('+')[1];
return string.Format("{0}:{1}:{2}", mytimespan.Hours
+ (mytimespan.Days*24),mytimespan.Minutes,mytimespan.Seconds);
static void Main(string[] args)
{
String timeText = "3/23/2015 12:00:13 AM";
String timeText2 = "3/23/2015 1:45:03 AM";
DateTime time = Convert.ToDateTime(timeText);
string temp = time.ToString("HH:mm:ss");
DateTime time2 = Convert.ToDateTime(timeText2);
string temp2 = time2.ToString("HH:mm:ss");
TimeSpan t1 = TimeSpan.Parse(temp);
TimeSpan t2 = TimeSpan.Parse(temp2);
Console.Out.WriteLine(t1 + t2); // 01:45:16
Console.ReadLine();
}

Categories