DateTime is not equal [duplicate] - c#

This question already has answers here:
Is there any difference between DateTime in c# and DateTime in SQL server?
(3 answers)
Closed 7 years ago.
I have next code:
DateTime endTime = DateTime.Now.AddDays(30);
InsertIntoDatabase(endTime);
var row = Db.SelectRow("select endTime from MyTable Where #column=myval", columnValue);
Assert.Equal(row["endTime"], endTime); // This is false! Why?
Assert is false.
And dates are different for some reason on milliseconds. Why???
endTime:
Date {7/17/2015 12:00:00 AM} System.DateTime
Day 17 int
DayOfWeek Friday System.DayOfWeek
DayOfYear 198 int
Hour 1 int
Kind Unspecified System.DateTimeKind
Millisecond 370 int
Minute 21 int
Month 7 int
Second 27 int
Ticks 635726928873700000 long
+ TimeOfDay {01:21:27.3700000} System.TimeSpan
Year 2015 int
row["endTime"]:
Date {7/17/2015 12:00:00 AM} System.DateTime
Day 17 int
DayOfWeek Friday System.DayOfWeek
DayOfYear 198 int
Hour 1 int
Kind Local System.DateTimeKind
Millisecond 371 int
Minute 21 int
Month 7 int
Second 27 int
Ticks 635726928873716049 long
+ TimeOfDay {01:21:27.3716049} System.TimeSpan
Year 2015 int
WHY???

Maybe this (Difference between DateTime in c# and DateTime in SQL server) will help a little.
you can also use Datetime2 for SQL

Looks like a rounding error to me, the DateTime has ticks of 635726928873700000 whereas the Row has 635726928873716049. This is probably due to differing levels of precision in the database vs DateTime.
The differences in ticks means they are different DateTimes.

Related

Compare two DateTimes with ignoring seconds and milliseconds

I take two object from database. One is a filename with date init and second one is a DateTime object like 2021-08-08 17:32:07.880.
First, I converted filename to datetime with the code shown here:
var fileDate = DateTime.ParseExact(filename, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
I have to check that the difference between the first date and the second date is 3 hours 15 min or simply 3 hours.
How do I delete seconds and milliseconds of date 2, and compare them?
I'd go similar to MatJ's recommendation:
You've got your file time, and your DB time, which might have seconds and milliseconds on it. If you do the later one minus the earlier one you get a timespan representing the length of time between the datetimes
dBDate - fileDate
Timespans have a TotalMinutes property that is a decimal. A timespan of 5 minutes 45 seconds would have a TotalMinutes of 5.75
So, if we cast that to an int it cuts off the seconds; simples!
var t = (int)((dBDate - fileDate).TotalMinutes);
Now you can compare your t for equality to 180 (3h) or 195 (3h15h
It is very easy to do !
Try following code :
TimeSpan timeSpan = (firstDate - secondDate)
timeSpan.CompareTo(new TimeSpan(3, 15, 0)) // hrs, mins, seconds
This CompareTo method will return 1 if difference between two times is greater than 3 hrs and 15 mins, otherwise, it will return -1
PS:
firstDate and secondDate are in DateTime

C# date rolling 13 months values in global variable .NET

In C# how do I get the below datetime values in .NET. I am trying to look at todays date and trying to get a rolling 13 months. So last month minus 13 months which is december 2017 but need to get first day of the month at 00:00:00.000. Also trying to get an enddate as below which is end of last month.
Trying to get this and assign it to a variable in my code.
StartDate:
2017-12-01 00:00:00.000
EndDate:
2019-01-31 23:59:59.000
Whats the best way to get this?
Here you go
DateTime mydate = DateTime.Today;
//2017-12-01 00:00:00.000
DateTime StartDate = new DateTime(mydate.Year, mydate.Month, 1).AddMonths(-14);
//2019-01-31 23:59:59.000
DateTime EndDate = new DateTime(mydate.Year, mydate.Month, 1).AddSeconds(-1);
You can get the date with DateTime date = DateTime.Today.AddMonths(-14).AddDays(-(DateTime.Today.Day - 1));
.AddMonths(-13) yielded january 2018 for me

Calculating for remaining days in current month [duplicate]

This question already has answers here:
How to find the first day of next month,if the current month is december
(12 answers)
Calculate difference between two dates (number of days)?
(17 answers)
Closed 5 years ago.
I would like to know how to calculate the remaining days of the month e.g (15 Feb 2017 to 28 Feb 2017) without the use of a datetimepicker set at 28 Feb 2017.
Here are my codes for subtraction of 2 datetimepicker:
DateTime startDate =
(DateTime)dateTimePicker2.Value;
DateTime endDate =
(DateTime)dateTimePicker1.Value;
TimeSpan ts = endDate.Subtract(startDate);
textBox10.Text = ts.Days.ToString();`
Here are the steps you need to go through:
take your current date
use DateTime.AddMonths() to generate a new date one month from your current date
create a new date that uses 1 for the day, and the month and year from the future date you just worked out
subtract your current date from the future date, this will give you a Timespan which contains the number of days difference
You can use the closely related question Calculate difference between two dates (number of days)? as a guide.
Here is an example, but you can use the Value property from your DateTimePicker instead. DateTime.DaysInMonth(int year, int month) is a helpful method.
DateTime beginDate = new DateTime(2017, 2, 15);
var daysLeft = DateTime.DaysInMonth(beginDate.Year, beginDate.Month) - beginDate.Day;
Console.WriteLine("days from Feb 15 to Feb 28: {0}", daysLeft);
Output:
days from Feb 15 to Feb 28: 13
You can try:
DateTime dt = DateTime.Now;
int days = dt.AddDays(1 - dt.Day).AddMonths(1).AddDays(-1).Day - dt.Day;

Subtracting timespan from 24 hours

I'm trying to subtract my potentially negative timespan values from 24 hours to change them into positive values.
As an example case:
I want to find how much time is there till 8:00 AM.
If it's 16:00 PM now, timespan gives me -8 ish value so I want to substract it from 24 to get 16.
I'm trying this but it's giving me this error
The DateTime represented by the string is not supported in calendar
System.Globalization.GregorianCalendar.
What I tried ;
string startTime = String.Format("{0:t}", "8:00");
TimeSpan timeLeft = Convert.ToDateTime(startTime).Subtract(DateTime.Now);
if (timeLeft.TotalMinutes < 0 )
{
timeLeft = Convert.ToDateTime(String.Format("{0:H}","24:00")).Subtract(Convert.ToDateTime(timeLeft.Negate())) ;
}
How can I achieve subtracting my potentially negative timespans from 24 hours?
You are confusing TimeSpan and DateTime. I guess there is an easier way:
var eightOClock = TimeSpan.FromHours(8);
var now = DateTime.Now;
var till8again = now.TimeOfDay > eightOClock
? TimeSpan.FromHours(32) - now.TimeOfDay
: eightOClock - now.TimeOfDay;
So if TimeOfDay is less than eight hours (it's before 8am), we take the difference to 8am. If it's greater than 8am, we take the difference to 32hours, which is 8am tomorrow.
A DateTime is an absolute date, happening at a certain day, month, year... It must not be used to represent a specific hour.
So your attempt to convert "8:00", or "24:00" in a DateTime will forcibly fail.
For this you must use TimeSpan (or eventually an integer if you always work with hours).
You can use for example
if(DateTime.Now.TimeOfDay > TimeSpan.FromHours(8))
To see if it's more or less than 8:00.
TimeOfDay will return you the amount of time elapsed for today since midnight.
DateTime has also a lot of useful methods to Add or Substract time, see https://msdn.microsoft.com/fr-fr/library/system.datetime(v=vs.110).aspx for details
Use TimeSpan, and if the startDate is less the Now, add a day to it and then make the comparison.
TimeSpan startTime = new TimeSpan(8,0,0);
TimeSpan now = DateTime.Now.TimeOfDay;
startTime = startTime < now ? startTime.Add(TimeSpan.FromDays(1)) : startTime;
TimeSpan diff = startTime - now;
Another point: the error is coming from the fact that 24:00 doesn't represent 12:00 midnight. 0:00 represents midnight, and that will be a valid DateTime.

C# - Compute total hours between 8:00 to 2:00 AND 8:00 to 12:00

Here's my code
DateTime TimeIn = "8:00 AM",
TimeOut="2:00 AM";
double Total;
private void compute()
{
Total = (TimeOut - TimeIn).TotalHours;
}
8:00am to 2:00am should result 18 hours.But mine is resulting -7
Another problem is when i typed 24:00 as time out C# couldn't recognize it as Time.
It works properly when the TimeOout is less than 12:00am. like 11:59pm backwards.
(eg.: 11:30PM - 8:00AM) it computes properly.
Please Help.
Add +24 hours when negative result.
may be this could help you:
string TimeIn= "8:00 AM";
string TimeOut= "2:00 AM";
TimeSpan duration = DateTime.Parse(TimeOut).Subtract(DateTime.Parse(TimeIn));
The way you have declared the datetime Value is wrong. The right way to do it is by converting the string to datetime format
DateTime TimeIn = Convert.ToDateTime("08:00");
DateTime TimeOut = Convert.ToDateTime("02:00");
TimeSpan ts = TimeIn - TimeOut;
If you need the 18 hours span that you're looking for you'll have to pass the date value as well while assigning data to the variables

Categories