Best method to find difference between two DateTime objects? [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I want to find difference between two DateTime objects. I know I can use DateTime.Subtract() and overloaded operator '-' (e.g DateTime - DateTime). But someone told me that these two techniques are not good enough, and there is a method DateDiff or something, which I should use and which is best to use. I want to know if it is true? If it is, then how the above two are inferior from any perspective?

DateDiff does not compare dateTime instances.
It compares specific parts of the DateTime instances - for example, the months, or hours.
For instance:
var lasyDayOf2018 = new DateDime(2018, 12, 31);
var firstDayOf2019 = lasyDayOf2018.AddDays(1);
var monthDiff = DateDiff(DateInterval.Month, lasyDayOf2018, firstDayOf2019)
monthDiff will be 1, even though only one day has passed between the two dates.
It's documented in the Remarks section of the DateDiff documentation page:
If Interval is set to DateInterval.Year, the return value is calculated purely from the year parts of Date1 and Date2. Similarly, the return value for DateInterval.Month is calculated purely from the year and month parts of the arguments, and for DateInterval.Quarter from the quarters containing the two dates.
For example, when comparing December 31 to January 1 of the following year, DateDiff returns 1 for DateInterval.Year, DateInterval.Quarter, or DateInterval.Month, even though at most only one day has elapsed.
To get the actual difference between different instances of DateTime, either use Subtract or -, as you wrote in the question.

Whether or not there is a problem, and the solution to that problem really depends on the situation and why you're computing the difference. There are two main problems with DateTime.Subtract() and operator -.
The first is that they both ignore the time zone portion of the data. So, for example, if you have two dates, 2019-07-18 12:00:00 UTC and 2019-07-18 06:00:00 MDT (local time), even though they represent the same moment in time (as measured from different time zones), DateTime.Subtract() will tell you that they're 6 hours apart.
The second problem is that you often want to know the answer in terms of units other than ticks, sometimes even something that cannot be converted to a fixed number of ticks. For example, if you want the difference in the months represented by two DateTimes, you cannot compute that from the difference in ticks (which is what DateTime.Subtract() is based on), because different months have different lengths. For example, for the dates '2019-06-30 23:59:59' and '2019-07-01 00:00:00' (in the same time zone) there is only a one second difference, but the months are different, so is the difference in months one or zero? It depends on what you want to use the answer for.

Related

How to delete rows in SQLite database where rows older than 30 days using c# ? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 13 days ago.
Improve this question
There is a SQLite data table with a lastVisited column which is REAL type .
I hope to delete rows using C# where lastVisited column are older than 30 days (This is a parameter, maybe it's 45, 60, or other), how can I do?
REAL is one the supported data type for storing dates :
SQLite does not have a storage class set aside for storing dates
and/or times. Instead, the built-in Date And Time Functions of SQLite
are capable of storing dates and times as TEXT, REAL, or INTEGER
values:
TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
REAL as Julian day numbers, the number of days since noon in Greenwich on November
24, 4714 B.C. according to the proleptic Gregorian calendar.
INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.
Julian days would be in the 2400000..2500000 range, and you can delete old values with something like :
DELETE ...
WHERE lastVisited < julianday('now') - 30

How do I split a string in 2 with a colon in? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 17 days ago.
This post was edited and submitted for review 17 days ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I have a textbox with an entry field, in which a user inputs time in a 00:00 format (HH:mm). What I would like to do is extract 2 integers from the string, the Hours (20:00 = 20 hours) and the minutes (00:20 = 20 minutes).
To clear things up, I tried using the string.Split() method with ":" as my delimiter. I was fetching my string from a TextMeshProUGUI Input Field in unity and when Split(); the resulting substring wouldn't convert into an Integer for some reason so I settled on using 2 separate (LEGACY) InputFields, one for hours one for minutes which works but is clunky.
I'm going to re-try my single InputField using the Legacy UI and the string.Split() method explained here.
Extending my comment into an answer. It seems like you're about to parse a string into a time which you can achieve with TimeSpan class and extract needed informations easily. For that you need to know what format your time input is and how you want to process it. Judging by your code I can assume you always expect a format of hh:mm which indicates that first part is an hour in 2 digit format ( either 02:mm or 14:mm ), same with minutes. This alone solves most of your problems because you can just parse your string into TimeSpan using ParseExact method:
// first, create a format you want to be used
const string FORMAT = "hh:mm";
// now just use TimeSpan.ParseExact method to retrieve your data
var result = TimeSpan.ParseExact(YourTextBoxText, FORMAT);
This will return a TimeSpan which has properties like Hours, Minutes etc. which you can then use to retrieve whatever time value you want.
EDIT: Things to note are that the above can throw a bunch of exceptions depending on the data input, formats etc. It's up to you if you're about to make any custom logic based on exception or whatever. Exceptions you might need to include in your logic and be aware of are
ArgumentNullException - thrown whenever argument is null,
FormatException - thrown whenever text input is in invalid format
For more info about TimeSpan you shold refer to the documentation
You could use the TimeSpan.Parse() function to convert the string to a TimeSpan.
Not the fastest method, but it's clean.
string time = "20:20";
if (TimeSpan.TryParse(time, out TimeSpan timespan))
{
// Do something with:
// timespan.Hours
// timespan.Minutes
}

How to ask C# date of birth in a certain format with limitations? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm very new to C# and I think I got something on my mind but can't quite figure it out.
So I got this school project that needs to ask the first name, last name and date of birth of the user but with certain limitations. I can figure the names out but the date problem persists.
The date of birth should be in DD.MM.YYYY. format and have certain limitations:
Date should be between 01-31
Month between 01-12
Year between 1900-2050
I can get it to ask but it won't specify the format and I don't know what variable to use.
To parse dates in custom format, DateTime.TryParse method is best fit.
You just need to find culture, which uses your date format, for example "fr-CH".
Then you use mentioned method to check if format of date was correct. It automatically checks if date is vaild, i.e. month is between 1 and 12, day of month is in correct range (1 through 28,29,30 or 31 depending on month and year).
You just need to additionally check the year.
Try this code (I used short-circuiting operator &&, so if parsing was successfull, then check the year):
DateTime dt;
CultureInfo culture = CultureInfo.CreateSpecificCulture("fr-CH");
DateTimeStyles styles = DateTimeStyles.None;
if(DateTime.TryParse("28.01.2018", culture, styles, out dt)
&& dt.Year >= 1900 && dt.Year <= 2050) // here you check additionally if year is in correct range
Console.WriteLine("Date successfully parsed!");

Setting up a date time [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I've been given an assignment by a friend for me to practise on C#. He wants me to set up a fitness counter, where he can add how many pushups/pullups etc he did, and then in a text file, print the date on which he entered that information (already done) and the amount of workout he did (already done). However, he also told me to set up a week and month system, where i will get everyday of his workout and print it as a whole in a weekly report, and then get all the weekly reports and print them as a month. I cant wrap my head around and find a way to approach this. How could i do it? Ive thought of getting each day from the file.txt and printing it out as a sum etc, but i cant find the appropriate code. Thanks a lot!
This is to get the day :
DateTime localDate = DateTime.Now;
Console.WriteLine("The date today is " + localDate.ToShortDateString());
Console.ReadLine();
And I've tried DateTime.Now.DayOfWeek; etc but nothing
What you can do for weeks is use the weeknumber. As there are different numbering systems, that isn't a property on 'DateTime' but is retrievable from a calendar. Use
CultureInfo ciCurr = CultureInfo.CurrentCulture;
int weekNum = ciCurr.Calendar.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
For months, you can retrieve the month property of the date. Remember that with these rules, weeks do not add up to month and year totals, as weeks van span two months or years.

How to convert DateTime.Now to this format? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am unable to understand how to convert DateTime.Now to some format such as 2015-06-04T14:13:00
What does T here represent and how to convert it to this format?
I'm really taking risk to answer that but..
You can escape the T character with single quotes and use a culture that have : as a TimeSeparator (eg: InvariantCulture) like;
DateTime.Now.ToString("yyyy-MM-dd'T'HH:mm:ss", CultureInfo.InvariantCulture);
As a better way, you can use The "s" standard format specifier which represents in SortableDateTimePattern property as a "yyyy'-'MM'-'dd'T'HH':'mm':'ss" custom string which is ISO 8601 representation.
DateTime.Now.ToString("s"); // 2015-06-22T15:17:27
What is T for exactly?
From https://en.wikipedia.org/wiki/ISO_8601#Combined_date_and_time_representations
A single point in time can be represented by concatenating a complete
date expression, the letter T as a delimiter, and a valid time
expression. For example "2007-04-05T14:30".
If a time zone designator is required, it follows the combined date
and time. For example "2007-04-05T14:30Z" or "2007-04-05T12:30-02:00".
Either basic or extended formats may be used, but both date and time
must use the same format. The date expression may be calendar, week,
or ordinal, and must use a complete representation. The time
expression may use reduced accuracy. It is permitted to omit the 'T'
character by mutual agreement.
and
By mutual agreement of the partners in information interchange, the
character [T] may be omitted in applications where there is no risk
of confusing a date and time of day representation with others defined
in this International Standard.

Categories