The best way to compare DateTime? - c#

The problem is the best way to compare DateTime form the past with now.
I try to diff a past of time with DateTime now but It's not absolutely solve my problem.
The function I have try is here =>
public void diffOfEpochTime(DateTime past_time){
double howlong = (DateTime.Now() - past_time).TotalDays;
Console.write(howlong/365.25 + " Year "
+ (howlong%365.25)/30 + " Month "
+ (howlong%365.25)%30 + " Day");
}
Seem like it's work but actually not because the diff of time is missed some of month and day.
Example the Time is January 1, 2018 12:00:00 AM
and today is March 1, 2018 12:00:00 AM
the answer should be 0 Year 2 Month 1 Day.
but the Function's answer is 0 Year 1 month 29 Day
Anyone have a suggestion to me how to dare with this, Thank you.

#Drag and Drop
Your answer about Noda Time library is solve my problem
=> Another answer
=> Noda time

Related

Humanizer for DateTime

I have this code:
Configurator.DateTimeHumanizeStrategy = new PrecisionDateTimeHumanizeStrategy(.75);
var dateTime1 = DateTime.UtcNow.AddYears(2).AddMonths(-5);
var text1 = dateTime1.Humanize();
In the text1 variable I get "one year from now". But this is not very accurate. Is there any way to get "one year and seven months from now"?
Update 1:
Solution #Daniel Hoffman has some problems, for example if my date is in the past:
//UtcNow is 11.07.2021
var dateTime6 = new DateTime(2021, 4, 24);
TimeSpan dateTimeSpan6 = dateTime6 - DateTime.UtcNow;
var text6 = dateTime6.Humanize();
string textSpan6 = dateTimeSpan6.Humanize(maxUnit: TimeUnit.Year, precision: 2);
then I get "2 months, 11 weeks" which contains basically the same information twice but in different units.
Update 2:
I have fixed the problem with dates in the past, by using Duration() method:
var timeSpan = date - DateTime.UtcNow;
return timeSpan.Duration().Humanize(maxUnit: TimeUnit.Year, precision: 2, minUnit: TimeUnit.Day);
[Edit]: Using TimeSpan will allow you to specify the precision of your period, but you will lose the ability to have "yesterday" or
"tomorrow", and it omits the " ago" or " from now", all of which are
localized.
A partial workaround would be to use the TimeSpan.Humanize
method for TimeSpans less than 366 days and DateTime.Humanize
otherwise. And if it's only going to be used in one language, the user
can append the appropriate text depending on if the timespan is
negative.
You can use the precision parameter with a TimeSpan:
TimeSpan periodFromNow = DateTime.UtcNow.AddYears(2).AddMonths(-5) - DateTime.UtcNow;
Then:
string myPeriodFromNow = periodFromNow.Humanize(maxUnit: TimeUnit.Year, precision: 2);
Other examples:
TimeSpan.FromDays(486).Humanize(maxUnit: TimeUnit.Year, precision: 7) => "1 year, 3 months, 29 days" // One day further is 1 year, 4 month
TimeSpan.FromDays(517).Humanize(maxUnit: TimeUnit.Year, precision: 7) => "1 year, 4 months, 30 days" // This month has 30 days and one day further is 1 year, 5 months
See also: https://github.com/Humanizr/Humanizer#humanize-timespan
It seems like its not currently possible in Humanizer to do what you want.
Check out this method PrecisionHumanize() on line 102, if the amount of days exceeds 365 then only years will be returned. And in general it seems like only one type of length of time can be returned, there is no years and months or minutes and seconds, just the largest one.
But check out another library called NodaTime it might be able to do what you want.
Here is a link to a different question similar to yours.

Minute give wrong values on substract

I want to subtract minutes and get the difference. below is my code
double diff = currBlock.EndTime.Subtract(currBlock.StartTime).TotalMinutes;
In given code (currBlock.StartTime = 23:30:00) and (currBlock.EndTime= 00:20:00)
here starttime is time of today i.e.(09/26/2016 23:30:00), night time which will be consider as 11:30 PM and endtime is time of tomorrow i.e.(09/27/2016 00:20:00), morning time which will be consider as 12:20 Am. In my code i am getting values in minus which is -1390 and it is incorrect. So please help me to solve this.
Here i have attach image of data for further reference.
please explain me properly, how do i use it? it is just a time block for different shift so there is no date include in it
There is a date included in it. You're telling us that EndTime is something like 09/27/2016 00:20:00, while StartTime is something like 09/26/2016 23:30:00. The problem is that that knowledge is in your head and not in your code. If you subtract the values as TimeSpans, then you're literally saying: what is 30 minutes minus 23 hours and 30 minutes. The answer, of course is -23 hours. To get the real difference, you must include the dates, which means utilizing a DateTime or DateTimeOffset type for both StartTime and EndTime, so you can encode that whole date and time. Then, when you do the subtraction, it will return the right value.
Below Code works for me. Thanks friends for your support and help.
string strCurrDate = (DateTime.Now.Date + currBlock.EndTime).ToString();
DateTime dtYourDate = DateTime.Parse((DateTime.Now.AddDays(-1).Date + currBlock.StartTime).ToString());
string strYourDate = dtYourDate.ToShortDateString() + " " + dtYourDate.ToLongTimeString();
string strTotalMinsElapsed = TotalMinutesElapsed(dtYourDate).ToString();
private long TotalMinutesElapsed(DateTime dtYourDate)
{
long lTotalMinutesElapsed = 0;
//Find Current Date and Time
DateTime dtCurrent = DateTime.Now;
//Find Time Difference details between current date and your given date
TimeSpan tsDiff = dtCurrent.Subtract(dtYourDate);
//Add Total Minutes for Days difference
lTotalMinutesElapsed = lTotalMinutesElapsed + tsDiff.Days * (24 * 60);
//Add Total Minutes for Hour difference
lTotalMinutesElapsed = lTotalMinutesElapsed + tsDiff.Hours * 60;
//Add Minutes
lTotalMinutesElapsed = lTotalMinutesElapsed + tsDiff.Minutes;
return lTotalMinutesElapsed;
}

Behavior of DateTime.AddYears on leap year

Can anyone explain the mathematical or simply the reasoning behind the leap year calculations in .NET when using AddYears method on DateTime?
If you take the 29th Feb 2012 and add a year, you get the 28th Feb 2013, not the 1st Mar 2013 (day before one year later).
If you add one year to 31st Jan 2012, you get 31st Jan 2013 (same date one year later).
I think most people would assume that "one year from 29.02.leapX is 01.03.leapX+1".
Example:
// Testing with 29th Feb
var now1 = DateTime.Parse("2012-02-29 15:00:00");
var results1 = new DateTime[]
{
now1.AddYears(1),
now1.AddYears(2),
now1.AddYears(3),
now1.AddYears(4)
};
foreach(var dt in results1)
{
Console.WriteLine(dt.ToString("s"));
}
// Output:
// 2013-02-28T15:00:00
// 2014-02-28T15:00:00
// 2015-02-28T15:00:00
// 2016-02-29T15:00:00
// Testing with 31st Jan
var now2 = DateTime.Parse("2012-01-31 13:00:00");
var results2 = new DateTime[]
{
now2.AddYears(1),
now2.AddYears(2),
now2.AddYears(3),
now2.AddYears(4)
};
foreach(var dt in results2)
{
Console.WriteLine(dt.ToString("s"));
}
// Output:
// 2013-01-31T13:00:00
// 2014-01-31T13:00:00
// 2015-01-31T13:00:00
// 2016-01-31T13:00:00
I think most people would assume that "one year from 29.02.leapX is 01.03.leapX+1".
I wouldn't. I would normally expect truncation. It's fundamentally similar to adding one month to January 30th - I'd expect to get the last day in February. In both cases, you're adding a "larger unit" (month or year) and a "smaller unit" (day) is being truncated to fit in with the year/month combination.
(This is how Joda Time and Noda Time behave too, btw.)
As Tim mentioned in comments, it's documented that way too:
The AddYears method calculates the resulting year taking into account leap years. The month and time-of-day part of the resulting DateTime object remains the same as this instance.
So the month has to stay as February; the year will change based on how many years are being added, obviously - so the day has to adjust to stay valid.
With your rationale then 1-Mar-2012 would become 2-Mar-2012 when you added a year. If you add this shift for all prior leap years then you are going to find your calculation massively adrift. The only sensible response is to return 28-Feb for non-leap years.
It is interesting, nether-the-less ..
e.g. this function is sometimes used:
private static int Age(DateTime birthDate, DateTime asAtDate)
{
// Calculate age in years
int age = asAtDate.Year - birthDate.Year;
if (asAtDate < birthDate.AddYears(age)) age--;
if (age < 0) age = 0;
return age;
}
If a person was born on 29Feb2016, this function is going to conclude they have reached age 1 on 28Feb2017.
I noted Excel Function examples as per:
=DATEDIF(DATE(2016,2,28),DATE(2017,2,28),"Y")
gives result of 1
=DATEDIF(DATE(2016,2,29),DATE(2017,2,28),"Y")
gives result of 0
=DATEDIF(DATE(2016,2,29),DATE(2017,3,1),"Y")
gives result of 1
=DATEDIF(DATE(2016,3,1),DATE(2017,3,1),"Y")
gives result of 1

c# find same range of "named days" from 1 year ago

using c# visual studio 2008.
Can anyone help with an algorithm to do this please
if i have a range of days selected for this week (eg monday to friday) i can find the dates for these using the datetime functions available.
What i want to do is compared to stored data for the same DAY range 1 year ago.
So basicly i need to go back 1 year and find the dates for the nearest Mon to fri DAY range from 1 year previous. I guess i also need to take into acount leap years.
Can anyone help with a suitable algorithm on how to achieve this.
Of course the DAY for todays date last year is not going to be the same day.
thanks in advance
Here's some code which might do what you want - but the test cases show that there are corner cases to consider:
using System;
public class Test
{
static void Main()
{
Console.WriteLine(SameDayLastYear(DateTime.Today));
Console.WriteLine(SameDayLastYear(new DateTime(2010, 12, 31)));
}
static DateTime SameDayLastYear(DateTime original)
{
DateTime sameDate = original.AddYears(-1);
int daysDiff = original.DayOfWeek - sameDate.DayOfWeek;
return sameDate.AddDays(daysDiff);
}
}
What would you want the result for the second call to be? This code returns January 1st 2010, because that's the closest date to "a year ago on the same day".
I strongly suggest that whatever you go with, you have unit tests checking leap years, start and end of year etc.
Let's say you select Wednesday 10-02-2010 - Friday 12-02-2010 this year.
Last year that would have been Tuesday 10-02-2009 - Thursday 12-02-2009.
So you can do the following: Go back a year by simply performing DateTime.AddYears(-1). Make sure you correct for leap years here.
Then you use .AddDays(1) until you end up on a Wednesday - Friday timeframe.
That way you only have to take leap years into account at one point and this should produce the result you need.
I just subtracted one year then ran backwards until I found a Monday. LastYear will end up being the first Monday before this date last year
DateTime LastYear = DateTime.Now.AddYears(-1)
DayOfWeek Check = LastYear.DayOfWeek;
while (Check != DayOfWeek.Monday)
{
LastYear = LastYear.addDays(-1);
Check = LastYear.DayOfWeek;
}
Console.WriteLine("{0}",LastYear);
DateTime now = DateTime.Now;
DateTime lastyear = now.AddYears(-1);
string dayOfWeek = lastyear.DayOfWeek.ToString();
if (dayOfWeek.Equals("Saturday")) { dayOfWeek = "Friday"; }
else if (dayOfWeek.Equals("Sunday")) { dayOfWeek = "Monday"; }
Console.WriteLine(dayOfWeek);
Console.ReadKey();
Get a datetime object for last year, then use the DayOfWeek property.
This was pretty fun.
// today's info
DateTime today = DateTime.Now;
DayOfWeek today_name = today.DayOfWeek;
// this day one year ago
DateTime year_ago = today - new TimeSpan( ((today.Year - 1) % 4) ? 365 : 366, 0, 0, 0);
// find the closest day to today's info's name
DayOfWeek today_name_a_year_ago = year_ago.DayOfWeek;
DateTime current_range_a_year_ago = year_ago - new TimeSpan( year_ago.DayOfWeek - today_name, 0, 0, 0);
Console.WriteLine( "Today is {0}, {1}", today_name, today);
Console.WriteLine( "One year from today was {0}, {1}", today_name_a_year_ago, year_ago);
Console.WriteLine( "New date range is {0}", current_range_a_year_ago);
I would highly recommend using the unit testing features built into VS2008 to make sure you account for corner cases.

how to get the 12 hour date from DateTime

when i get the DateTime.Hour property, i always get the 24 hour time (so 6PM would give me 18).
how do i get the "12 hour" time so 6PM just gives me 6.
i obviously can do the check myself but i assume there is a built in function for this.
How about:
DateTime.Hour % 12
That will give 0-11 of course... do you want 1-12? If so:
((DateTime.Hour + 11) % 12) + 1
I don't think there's anything simpler built in...
DateTime.Now.ToString("hh"); --> Using this you will get "06" for 18h.
I don't know of any built in method, but you can always add an extension method to accomplish this.
Of course, you could always replace the code with the way you want to accomplish it.
public static class Extension
{
public static int GetTwelveCycleHour(this DateTime dateTime)
{
if (dateTime.Hour > 12)
{
return dateTime.Hour - 12;
}
return dateTime.Hour;
}
}
What about simply:
public static int GetTwelveCycleHour(this DateTime dateTime)
{
return Convert.ToInt32(dateTime.ToString("h"));
}
There's no built-in function, mainly because you shouldn't need it:
If you're doing this for output to the user, look at using a format string.
If you're doing this for a calculation, you can subtract datetimes or add timespans directly.
Outside of this, the math calculation is simple enough and already available in other answers here.
I thought the most convenient answer was submitted by Jon Skeet. The below is the same but converted to Visual Basic. I like things to be super easy. It took me a few to figure out the C# to Visual Basic Conversion. I included some 'extra' stuff as well. Hope this saves someone else time.
Visual Basic
(((DateTime.Now().Hour + 11) Mod 12) + 1)
Extra
Dim stringDate = DateTime.Now().Year &
DateTime.Now().Month.ToString("00") &
DateTime.Now().Day.ToString("00") & "_" &
(((DateTime.Now().Hour + 11) Mod 12) + 1).ToString("00") &
DateTime.Now().Minute.ToString("00")
The ToString("00") forces each Month/Day/Hour/Minute to always be represented by two digits.
Year = 2019
Month: April 4 = 04
Day: 3 = 03
Hour: 10 = 10
5 Minutes = 05
stringDate = 201904031005
DateTime date = Convert.ToDateTime("12/12/2022 20:20:00 PM");
var hour = date.Hour;
var dateTime = Convert.ToDateTime((date.ToShortDateString() + " " + hour + ":00:00"));
Console.WriteLine(dateTime); // 12/12/2022 8:00:00 PM
Console.WriteLine(hour); // 20

Categories