Calculate minutes from a certain time to current time c# [duplicate] - c#

This question already has answers here:
What is the easiest way to subtract time in C#?
(7 answers)
Closed 8 years ago.
I have a certain time ie. 10.30 AM. The user makes entry in a table. If the user makes entry after 10.30 AM , then the number of minutes from 10.30 Am to the current time should be calculated and set to a string.
Here is what I tried uptil now:-
int hour = DateTime.Now.Hour;
int mins = DateTIme.Now.Minute
if(hour>10 && mins >30)
{
string lateBy = "You are late by:"+ //????? how do I calculate this?
}
Any help would be great

Use TimeSpan to find the difference between the 2 datetime values, and use the TotalMinutes property to get the difference in minutes.
DateTime today = DateTime.Today;
DateTime start = new DateTime(today.Year,today.Month,today.Day,10,30,00);
DateTime now = DateTime.Now;
int hour = now.Hour;
int mins = now.Minute;
TimeSpan ts = now.Subtract(start);
if(ts.TotalMinutes > 0) //Time now is after 10:30
{
string lateBy = "You are late by:"+ ts.TotalMinutes.ToString();
}

Ignoring dates and assuming it is always the same day as the 10:30 deadline day:
string lateBy = "You are late by:"+ ((hour-10)*60 + mins-30) + " minutes";
Note this only works before midnight, i.e. for the same day.

Since both are DateTime, you can make use of DateTime.Subract
DateTime a = new DateTime(2014, 06, 20, 10, 30, 00);
DateTime b = DateTime.Now;
Console.WriteLine("You are late by:"+b.Subtract(a).TotalMinutes +"minutes");
Console.ReadLine();

Related

Round up DateTime

For my SteamBot I want to store the date and the time when the item is tradable again.
Example:
// DateNow = 05.06.2019 13:37:00
(+ 7 days due to Steam's trade policy)
// DateNow+7Days = 12.06.2019 13:37:00
// DateIneed = 13.06.2019 09:00:00
So the DateTime I need is CurrentDateTime + 7 Days + The rest to 9 o'clock
This is how far I come:
var date = DateTime.Now.AddDays(7);
Is there any smart way to always get the DateTime I need?
Language is C#
You can check if it is before 9 o'clock today, then set the time to 9, else add one day and set the time to 9, should be fairly easy I think.
var time = DateTime.Now;
var date = time.Hour <= 9
? time.Date.AddDays(7).AddHours(9)
: time.Date.AddDays(7).AddHours(9).AddDays(1);
The DateTime.Date field exposes just the date of a DateTime, you can then add an arbitrary TimeSpan to that to set the time of a DateTime object to whatever you want;
DateTime.Now.AddDays(7).Date.Add(new TimeSpan(9, 0, 0))
Check it out in action here: https://dotnetfiddle.net/l3X37y
Given the hour of the day may be past 9AM already, it's possible to end up with a DateTime less than 7 days, to counter this you can check if the hour of the day exceeds what you're going to set the DateTime to and add a day if it does, like so;
DateTime dt = DateTime.Now.AddDays(7);
dt = dt.Date.Add(new TimeSpan(dt.Hour >= 9 ? 1 : 0, 9, 0, 0))
See this one in action here: https://dotnetfiddle.net/lfVGis

How To get Interval Between Two Datetime (Timestamp) [duplicate]

This question already has answers here:
Date Difference in ASP.Net
(6 answers)
Closed 3 years ago.
I organized a program which started on 31st December 2018 at 10:00pm hence its been four months ago, i want a way to find this duration by code.
for example , how youtube is able to tell when a comment was written(eg,4years ago,5 months ago).
You can simply substract a DateTime object from another, which results in a TimeSpan representing the difference:
DateTime x = DateTime.Now;
DateTime y = DateTime.Today;
TimeSpan difference = x - y;
var programStartDateTime = new DateTime(2018, 12, 31);
var timeSpan = DateTime.Now - programStartDateTime;
Console.WriteLine($"The difference is: {timeSpan.ToString()}");
I think below sample code may help you
DateTime date1 = DateTime.Now;
DateTime date2 = DateTime.Now.AddDays(-1);
TimeSpan time = date1 - date2;
WriteLine($"TimeSpan : {time}" );

Get the days of year and all the hours between 2 dates in C#

I have folder structures like Year (2016)->day of year (308,309) -> hour in the day (00 to 23). I want to know how to get all the days and hours between 2 dates say between today 9am and yesterday 10am. Is there an easy way to do this?
My bad! I didn't give enough information. So I did try Span before I asked this and I don't want to get the different like the span.days, hours or mins instead i want the days of the year and hours between 2 dates.
like between yesterday 10 am and today it will 307th day 10th hour,11th hour and so on... until today 308th day and 9th hour. I can do this by looping thru the dates but i wanted to know if there is a straight forward way.
I would create a simple class for storing the data you need:
class DateInfo
{
public string Year {get;set;}
public string DayOfYear{get;set;}
public string Hour {get;set;}
}
and then get the results:
DateTime d1 = DateTime.Today.AddDays(-1).AddHours(10);
DateTime d2 = DateTime.Today.AddHours(9);
IList<DateInfo> dates = new List<DateInfo>();
while (d1 <= d2)
{
DateInfo dateInfo = new DateInfo()
{
Year = d1.ToString("yyyy"),
DayOfYear = d1.DayOfYear.ToString(),
Hour = d1.ToString("HH"),
};
dates.Add(dateInfo);
d1 = d1.AddHours(1);
}
There would be n number of ways to find out the difference between two dates. 2 of them are as follows
DateTime a = new DateTime(2016, 11, 03, 10, 00, 00);
DateTime b = DateTime.Now;
Console.WriteLine(b.Subtract(a).TotalHours);
This will give you the total hours between two dates Where as
TimeSpan span = (b - a);
Console.WriteLine(String.Format("{0} days, {1} hours, {2} minutes, {3} seconds", span.Days, span.Hours, span.Minutes, span.Seconds));
This will give you the details in the format which everyone can understand.

Year, Month, Day differ counter(Date) in C#

I was wondering if there was already an implemented Datecounter which will count how many years, month and days it differs from a date to another? And if there is a difference, the function will count how many years, month and days in difference and store it and we only need to use Console.Writeline(timecomparer.yearDiffCounter); to tell them how many years it is in difference
For example (pseudocode, not 100% correct)!
Date date1 = new Date("2013-07-05");
Date date2 = new Date("2010-07-05");
TimeComparer compare = new TimeComparer();
compare.differDate(date1,date2); //here it will count and give 3 years difference
Using Noda Time:
LocalDate date1 = new LocalDate(2013, 07, 05);
LocalDate date2 = new LocalDate(2010, 07, 05);
Period period = Period.Between(date2, date1, PeriodUnits.YearMonthDay);
Console.WriteLine("{0} years, {1} months, {2} days",
period.Years, period.Months, period.Days);
// "3 years, 0 months, 0 days"
Powerful solution for time is Noda Time by Jon Skeet.
public string DateDiff(DateTime DateTime1, DateTime DateTime2)
{
string dateDiff = null;
TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
TimeSpan ts = ts1.Subtract(ts2).Duration();
dateDiff = ts.Days.ToString() + "day"
+ ts.Hours.ToString() + "hours"
+ ts.Minutes.ToString() + "minutest"
+ ts.Seconds.ToString() + "seconds";
return dateDiff;
}
my way you can change.
Boolean operations on DateTime objects in C# yield TimeSpan objects
DateTime Yesterday = DateTime.Now().AddDays(-1);
DateTime Today = DateTime.Now();
TimeSpan difference = Today - Yesterday;
A timespan can then tell you how many days, hours, minutes, seconds etc it has.
If you want years from a Timespan, see this answer by brianary

how to subtract previous date from current date using c# [duplicate]

This question already has answers here:
C#: how do I subtract two dates?
(11 answers)
Closed 10 years ago.
i want to subtract previous date from current date. previous date may be 2 months and 15 days or 1 year 9 month and 10 days... like this etc... So please how can i write the Coding in C#. thanks a lot.
Any answer using TimeSpan will not be able to give you "2 months and 15 days" - as the length of a month changes over time.
Doing this using the base class libraries is a pain... which is one of the reasons I started the Noda Time project. Amongst its other features, it allows you to determine the Period between to dates (or dates and times, etc).
For example, let's see how long I've been on Stack Overflow:
LocalDate today = new LocalDate(2013, 2, 8);
LocalDate start = new LocalDate(2008, 9, 26);
// This defaults to using year, month, day units. You can specify alternatives.
Period period = Period.Between(start, today);
Console.WriteLine("{0} years; {1} months; {2} days",
period.Years, period.Months, period.Days);
Output:
4 years; 4 months; 13 days
Or if you actually wanted to subtract a period from a date (the question isn't very clear) you can do that too:
Period period = new PeriodBuilder { Years = 4, Months = 4, Days = 13 }.Build();
LocalDate today = new LocalDate(2013, 2, 8);
LocalDate start = today - period;
Console.WriteLine(start);
Output:
25 September 2008
Note that this doesn't give September 26th, because of the somewhat crazy nature of date/time arithmetic. If you added the period to September 26th you'd get today... but that's not the same thing. Treat this as a warning that you need to be really careful about describing what you want to achieve :)
This second side you can do with the BCL fairly easily though:
DateTime today = new DateTime(2013, 2, 8);
DateTime start = today.PlusYears(-4).PlusMonths(-4).PlusDays(-13);
There's no BCL type to represent that "years, months, days" value though.
Your question is a little confusing. Do you want to subtract one date from another date, or do you want to subtract a period of time from a date.
1. Subtract one date from another date:
DateTime previousDate = new DateTime(1990, 12, 12);
DateTime currentDate = DateTime.UtcNow;
TimeSpan difference = currentDate - previousDate;
You can then use the TimeSpan methods to get the difference in various units of time as you like.
Here's more info on TimeSpan: http://msdn.microsoft.com/en-us/library/system.timespan.aspx
2. Subtract a period of time from a date
DateTime currentDate = DateTime.UtcNow;
TimeSpan periodOfTime = new TimeSpan(12, 12, 0, 0);
DateTime newDate = currentDate - periodOfTime;
However, you'll have to calculate yourself what the length of a month is, if that's what you want.
You can use DateTime.Subtract.
Examples from article:
System.DateTime date1 = new System.DateTime(1996, 6, 3, 22, 15, 0);
System.DateTime date2 = new System.DateTime(1996, 12, 6, 13, 2, 0);
System.DateTime date3 = new System.DateTime(1996, 10, 12, 8, 42, 0);
// diff1 gets 185 days, 14 hours, and 47 minutes.
System.TimeSpan diff1 = date2.Subtract(date1);
// date4 gets 4/9/1996 5:55:00 PM.
System.DateTime date4 = date3.Subtract(diff1);
// diff2 gets 55 days 4 hours and 20 minutes.
System.TimeSpan diff2 = date2 - date3;
// date5 gets 4/9/1996 5:55:00 PM.
System.DateTime date5 = date1 - diff2;
TimeSpan timeSpan = new TimeSpan(2,2,0);
DateTime dateTime = DateTime.Now.Subtract(timeSpan);
When you subtract two date in C# you get a TimeSpan object.
You can acces different properties of it to get the actual days, hours, minutes etc. taht it represents:
DateTime a;
DateTime b;
//assign some values
TimeSpan span = a.Subtract(b);
Console.WriteLine("Days: " + span.Days);
The following should do.
TimeSpan diff = DateTime.Now - previousDate;

Categories

Resources