These are the variables I'm using:
var start = new DateTime();
var End = new DateTime();
Help me out by validating with if condition.
If I am understanding correctly you will have to try something like
if (start.AddDays(5) == End)
DateTime.AddDays Method
You can calculate a TimeSpan between the two dates and use properties of TimeSpan to determine how far apart they are, e.g.
TimeSpan diff = new TimeSpan(End.Ticks - start.Ticks);
double daysApart = diff.TotalDays;
if (daysApart >= 5.0) // Do stuff (assumes you want at least 5 days)
if(end.Subtract(start).Days > 5)
You should familiarize yourself with the DateTime structure. For this in particular the AddDays method or depending on how you end up doing things the Subtract method.
// Setting end date to start date plus 5 days
var start = new DateTime();
var end = start.AddDays(5)
// Testing if end date is the same as start date plus 5 days
if (start.AddDays(5) == end)
{
// It true!
}
/// or like so...
if (end.subtract(start).Days >= 5)
{
// It true!
}
Try this:
TimeSpan elapsed;
elapsed = end.Subtract(start);
if (elapsed.Days > 5)
//Do stuff
http://www.dotnetperls.com/datetime
Related
I'm struggeling a bit with an algorithm implementation.
I am having a start date and an end date and I want to list all possible timespans within that timespan with a special condition as start and end dates.
For example:
My start date is 01-01-2020 and my end date is 31-01-2020. My condition is to list all possible timespans that have at least 7 days and maximum 10 days.
So the result set would be like:
01-01-2020 -> 08-01-2020
01-01-2020 -> 09-01-2020
...
02-01-2020 -> 09-01-2020
...
24-01-2020 -> 31-01-2020
Preferable as Linq so I can enumerate.
Here's a simple implementation. It's not the most efficient, but it's easy to understand:
public static IEnumerable<(DateTime start, DateTime end)> ListTimespans(DateTime startDate, DateTime endDate, int minDays, int maxDays)
{
// Loop through all of the possible starts. The first day we can start on is startDate,
// and the last day we can start on is endDate - minDays (which gives us a span
// minDays long ending on endDate)
for (var start = startDate; start <= endDate.AddDays(-minDays); start = start.AddDays(1))
{
// For each of these starts, loop through the possible end dates. There are two
// limits to the end date: either hit the maximum number of days for a span
// (start.AddDays(maxDays)), or we hit the end date.
// Loop until whichever one comes first.
for (var end = start.AddDays(minDays); end <= Min(start.AddDays(maxDays), endDate); end = end.AddDays(1))
{
yield return (start, end);
}
}
DateTime Min(DateTime x, DateTime y) => x < y ? x : y;
}
See it in action here.
I am trying to create script that checks is the current time passed, but getting some errors.
DateTime currentTime = DateTime.Now;
TimeSpan pauseMin = TimeSpan.FromMinutes(1);
TimeSpan compare = currentTime + pauseMin;
if (currentTime >= compare)
return null;
I would write this as
DateTime currentTime = DateTime.Now;
TimeSpan pauseMin = TimeSpan.FromMinutes(1);
DateTime compare = currentTime.Add(pauseMin);
if (currentTime >= compare) {
return null;
}
This uses the type of object that you are trying to represent with everything. DateTime's can have Timespan's added to them: https://msdn.microsoft.com/en-us/library/system.datetime.add%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
Or Istern's answer if you are always just adding an integer of minutes to the time.
You can't compare DateTime and TimeSpan.
Try
var compare = currentTime.AddMinutes(1)
If you need to somehow use TimeSpan, use Jamie F's answer.
DateTime and TimeSpan is different. You can use currentTime like this:
TimeSpan currentTime = TimeSpan.FromTicks(DateTime.Now.Ticks);
And you can get passed minutes like this:
double minutes = (compare - currentTime).TotalMinutes;
If you just want to pause for 1 minute, you can use
System.Threading.Thread.Sleep(1000 * 60); // 1 minute = 60000 milliseconds
If you want your function to run for 1 minute, you can use something like
var returnAt = DateTime.Now().AddMinutes(1);
while ( true )
{
// your code here ?
if ( DateTime.Now() >= returnAt ) return null;
}
I have been trying to use an ajax CalenderExtender for my application.
I have many small operations in my app like adding duration to start date of a task to find the finish date, change duration of a task if its end date is changed (depending on its start date),etc.
But while I do all these operations I want to skip all the holidays and saturday , sundays from the calculations for eg. a task starting on 01/23/2014 with a duration of 5 days should finish on 01/29/2014 (adding 2 days for sat n sun in duration) instead of 01/27/2014. Same should be performed on other operations as well.
Is there a way to do this?
For Sundays and Saturdays, it's easy. Just check the DateTime.DayOfWeek property of your dates.
If you have an operation that will start on date start and will end on date end, you can see what dates are Saturdays or Sundays like this:
List<DateTime> satsAndSundays;
for (DateTime temp = start; temp <= end; temp.AddDays(1))
{
if (temp.DayOfWeek == DayOfWeek.Sunday ||
temp.DayOfWeek == DayOfWeek.Saturday)
{
satsAndSundays.add(temp);
}
}
And since you can know how many days there are between start and end by doing something like:
TimeSpan span = end - start;
int totalDays = (int)span.TotalDays;
// TotalDays is actually a double, I'm just discarding the non integer part.
You may fid out how many work days you have there by doing totalDays - satsAndSundays.Count.
Edit: I just read the question again. If you want a task to start on a given date, and take x work days, you can do it like this:
DateTime end = start;
for (int i = x; i >= 0;) // the third parameter of the for is empty on purpose
{
end = end.AddDays(1);
if (end.DayOfWeek != DayOfWeek.Saturday &&
end.DayOfWeek != DayOfWeek.Sunday)
{
i--;
}
}
Afther the loop, end will be x workdays after start (provided there are no holidays in between).
For holidays, though, there is no alghoritm for that in the framework. You need to fetch them from some source (a file, a database, a web service etc.). Or you could write your own program to figure them out - most holidays that are not on a fixed date do follow formulas when it comes to when they happen. Do take into account, however, that holidays may vary by culture and region. If your application is to be used throughout a country, for example, it may be quite the effort to implement city-wide holidays. Depending on your needs, it might even be better to either let the users input which days are holidays, or making your own database your app can access and use.
Try this one..
private string GetDatesOfSundays(DateTime DatMonth)
{
string sReturn = "";
int iDayOffset = DatMonth.Day - 1;
DatMonth = DatMonth.AddDays(System.Convert.ToDouble(-DatMonth.Day + 1));
DateTime DatMonth2 = DatMonth.AddMonths(1).AddDays(System.Convert.ToDouble(-1));
while (DatMonth < DatMonth2)
{
if (DatMonth.DayOfWeek == System.DayOfWeek.Sunday)
{
if (sReturn.Length > 0) sReturn += ",";
sReturn += DatMonth.ToShortDateString();
}
DatMonth = DatMonth.AddDays(1.0);
}
return sReturn;
}
How to check if 20 minutes have passed from current date?
For example:
var start = DateTime.Now;
var oldDate = "08/10/2011 23:50:31";
if(start ??) {
//20 minutes were passed from start
}
what's the best way to do this?
Thanks :)
You should convert your start time to a UTC time, say 'start'.
You can now compare your start time to the current UTC time using:
DateTime.UtcNow > start.AddMinutes(20)
This approach means that you will get the correct answer around daylight savings time changes.
By adding time to the start time instead of subtracting and comparing the total time on a TimeSpan you have a more readable syntax AND you can handle more date difference cases, e.g. 1 month from the start, 2 weeks from the start, ...
var start = DateTime.Now;
var oldDate = DateTime.Parse("08/10/2011 23:50:31");
if ((start - oldDate).TotalMinutes >= 20)
{
//20 minutes were passed from start
}
var start = DateTime.Now;
var oldDate = DateTime.Parse("08/10/2011 23:50:31");
if(start.Subtract(oldDate) >= TimeSpan.FromMinutes(20))
{
//20 minutes were passed from start
}
Parse oldDate into a DateTime object (DateTime.Parse).
Subtract the parsed date from start. This will return a TimeSpan.
Inspect TotalMinutes.
I was able to accomplish this by using a JodaTime Library in my project. I came out with this code.
String datetime1 = "2012/08/24 05:22:34";
String datetime2 = "2012/08/24 05:23:28";
DateTimeFormatter format = DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss");
DateTime time1 = format.parseDateTime(datetime1);
DateTime time2 = format.parseDateTime(datetime2);
Minutes Interval = Minutes.minutesBetween(time1, time2);
Minutes minInterval = Minutes.minutes(20);
if(Interval.isGreaterThan(minInterval)){
return true;
}
else{
return false;
}
This will check if the Time Interval between datetime1 and datetime2 is GreaterThan 20 Minutes. Change the property to Seconds. It will be easier for you know. This will return false.
var end = DateTime.Parse(oldDate);
if (start.Hour == end.Hour && start.AddMinutes(20).Minute >= end.Minute)
I have a calendar which passes selected dates as strings into a method. Inside this method, I want to generate a list of all the dates starting from the selected start date and ending with the selected end date, obviously including all of the dates inbetween, regardless of how many days are inbetween the selected start and end dates.
Below I have the beginning of the method which takes the date strings and converts them into DateTime variables so that I can make use of the DateTime calculation functions. However, I cannot seem to work out how to calculate all of the dates inbetween the start and end date?
Obviously the first stage is to subtract the start date from the end date, but I cannot calculate the rest of the steps.
Help appreciated greatly,
kind regards.
public void DTCalculations()
{
List<string> calculatedDates = new List<string>();
string startDate = "2009-07-27";
string endDate = "2009-07-29";
//Convert to DateTime variables
DateTime start = DateTime.Parse(startDate);
DateTime end = DateTime.Parse(endDate);
//Calculate difference between start and end date.
TimeSpan difference = end.Subtract(start);
//Generate list of dates beginning at start date and ending at end date.
//ToDo:
}
static IEnumerable<DateTime> AllDatesBetween(DateTime start, DateTime end)
{
for(var day = start.Date; day <= end; day = day.AddDays(1))
yield return day;
}
Edit: Added code to solve your particular example and to demonstrate usage:
var calculatedDates =
new List<string>
(
AllDatesBetween
(
DateTime.Parse("2009-07-27"),
DateTime.Parse("2009-07-29")
).Select(d => d.ToString("yyyy-MM-dd"))
);
You just need to iterate from start to end, you can do this in a for loop
DateTime start = DateTime.Parse(startDate);
DateTime end = DateTime.Parse(endDate);
for(DateTime counter = start; counter <= end; counter = counter.AddDays(1))
{
calculatedDates.Add(counter);
}
The easiest thing to do would be take the start date, and add 1 day to it (using AddDays) until you reach the end date. Something like this:
DateTime calcDate = start.Date;
while (calcDate <= end)
{
calcDate = calcDate.AddDays(1);
calculatedDates.Add(calcDate.ToString());
}
Obviously, you would adjust the while conditional and the position of the AddDays call depending on if you wanted to include the start and end dates in the collection or not.
[Edit: By the way, you should consider using TryParse() instead of Parse() in case the passed in strings don't convert to dates nicely]
for( DateTime i = start; i <= end; i = i.AddDays( 1 ) )
{
Console.WriteLine(i.ToShortDateString());
}
An alternative method
public static class MyExtensions
{
public static IEnumerable EachDay(this DateTime start, DateTime end)
{
// Remove time info from start date (we only care about day).
DateTime currentDay = new DateTime(start.Year, start.Month, start.Day);
while (currentDay <= end)
{
yield return currentDay;
currentDay = currentDay.AddDays(1);
}
}
}
Now in the calling code you can do the following:
DateTime start = DateTime.Now;
DateTime end = start.AddDays(20);
foreach (var day in start.EachDay(end))
{
...
}
Another advantage to this approach is that it makes it trivial to add EachWeek, EachMonth etc. These will then all be accessible on DateTime.