How to make newTime as a global variable?
It should be added 30 minutes in time and use it in a condition. It is necessary to make var newTime as global var.
if (timerCheck == 0)
{
var today = DateTime.Now;
var interval = new TimeSpan(00, 30, 00);
var newTime = today + interval;
timerCheck = 1;
}
if (timerCheck == 1)
{
var today = DateTime.Now;
if (today >= newTime)
{
You can do it like this
public static class GlobalVariables
{
public static DateTime NewTime { get; set; }
}
Then call it like this:
if (today >= GlobalVariables.NewTime)
Just move it outside if.
I don't test it, but It might work.
DateTime newTime;
if (timerCheck == 0)
{
var today = DateTime.Now;
var interval = new TimeSpan(00, 30, 00);
newTime = today + interval;
timerCheck = 1;
}
if (timerCheck == 1)
{
if (newTime.Equals(default(DateTime)) return; // don't sure is it required or not
var today = DateTime.Now;
if (today >= newTime)
{
Well i think you should put it outside the body of If first as a variable then use it in the condition.
Related
What I want to do is basically in the question title.
This is what I've tried so far, unsuccessfully.
Note that I haven't implemented exact hour and minute yet (9:30 pm).
It actually seems to always return a value between 00:00:59 and 00:00:01 for some reason
DateTime nextSunday = DateTime.Today.AddDays(((int)DayOfWeek.Sunday - (int)DateTime.Today.DayOfWeek + 7) % 7) + new TimeSpan(21, 30, 0);
TimeSpan untilNextSunday = nextSunday - DateTime.Now;
await ReplyAsync($"It is in **{TimeSpan.FromSeconds(untilNextSunday.Seconds)}**");
Which equals to
var today = DateTime.Today;
var daysUntilSunday = ((int)DayOfWeek.Sunday - (int)today.DayOfWeek + 7) % 7;
var nextSunday = today.AddDays(daysUntilSunday);
var ts = new TimeSpan(21, 30, 0);
nextSunday = nextSunday.Date + ts;
TimeSpan untilNextSunday = nextSunday - DateTime.Now;
If possible, I'd also like to use Paris TimeZone.
I tend to find all of the DateTime.Today.AddDays(((int)DayOfWeek.Sunday - (int)DateTime.Today.DayOfWeek + 7) % 7) + new TimeSpan(21, 30, 0) arithmetic quite confusing. Instead I try to go with a more iterative approach that can be clearly reasoned about.
Try this:
public static DateTime GetNextDateTime(DateTime now, DayOfWeek targetDay, TimeSpan targetTime)
{
DateTime target = now.Date.Add(targetTime);
while (target < now || target.DayOfWeek != targetDay)
{
target = target.AddDays(1.0);
}
return target;
}
Now you can use it like this:
DateTime now = DateTime.Now;
DateTime target = GetNextDateTime(DateTime.Now, DayOfWeek.Sunday, new TimeSpan(21, 30, 0));
TimeSpan untilNextSunday = target.Subtract(now);
Here's an example using Noda Time, including time zone handling. It doesn't attempt to handle "interesting" situations where (say) you ask for the next 1:30am, and it's already 1:45am but the clock goes back at 2am - in which case the right answer is really "45 minutes" but this code will give you a week instead.
using System;
using NodaTime;
class Test
{
static void Main()
{
var duration = GetDurationToNext(
IsoDayOfWeek.Sunday, new LocalTime(21, 30),
DateTimeZoneProviders.Tzdb["Europe/Paris"],
SystemClock.Instance);
Console.WriteLine($"Duration: {duration}");
}
static Duration GetDurationToNext(
IsoDayOfWeek dayOfWeek,
LocalTime timeOfDay,
DateTimeZone zone,
IClock clock) // Or just take an instant
{
var now = clock.GetCurrentInstant();
var localNow = now.InZone(zone).LocalDateTime;
var localNext = localNow
.Date.With(DateAdjusters.NextOrSame(dayOfWeek))
.At(timeOfDay);
// Handle "we're already on the right day-of-week, but
// later in the day"
if (localNext <= localNow)
{
localNext = localNext.PlusWeeks(1);
}
var zonedNext = localNext.InZoneLeniently(zone);
var instantNext = zonedNext.ToInstant();
return instantNext - now;
}
}
I have the following code:
Dictionary<DayOfWeek, List<TimeSpan>> Daily = new Dictionary<DayOfWeek, List<TimeSpan>>();
The idea is that i can add a day with a time to the Daily dictionary. But a job can execute on the same day more than once.
so Daily can look like this:
{ "Monday" : [{"Hour":10, "Minute": 15}, {"Hour": 8, "Minute":5}] }
Now i would like to get the next execution datetime.
private void UpdateNextExecutionTime()
{
TimeSpan t = new TimeSpan(15, 15, 0);
DayOfWeek current = DateTime.Now.DayOfWeek;
DayOfWeek tmp = current;
TimeSpan time = new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
int cur = (int)current;
for(int i = 0; i < 7; i++) {
if(Daily.ContainsKey((DayOfWeek)cur)) {
tmp = (DayOfWeek)cur;
/* stuck */
continue;
}
cur++;
if (cur >= 7)
cur = 0;
}
}
I managed to get the first upcoming day (including today) in the Daily dictionary but i'm stuck on the getting the time.
How would i be able to do this?
Assuming t is the time you're using as the point at which you'd like to find the next execution time, put this where you have 'stuck' (edit; just realized you changed to using TimeSpan in your list):
var execTimes = Daily[tmp];
if (execTimes != null) {
var nextTime = execTimes.OrderBy(x => x).FirstOrDefault(x => x > t);
if (nextTime != default(TimeSpan)) {
// do something...
}
}
You can also have the day in the TimeSpan,
Here is a simple example the finds the next date:
var schedule = new List<TimeSpan>{
new TimeSpan(0,16,30,0),
new TimeSpan(1,16,30,0),
new TimeSpan(5,16,30,0)
};
var monday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + 1);
var fromMonday = DateTime.Now - monday;
var next = schedule.OrderBy(t => t).FirstOrDefault(t => t > fromMonday);
Console.Write(monday + next - DateTime.Now);
I need to check if DateTime.Now is in the first 3 business days of each month (from Mon - Fri). I also need to provide a List<DateTime> with national holidays and these should be handled accordingly.
If DateTime.Now is Saturday and is 1 of the month, first 3 business days are Monday, Tuesday, Wednesday (3, 4, 5 of the month).
public bool IsBusinessDay()
{
DateTime now = DateTime.Now;
DateTime fbd = new DateTime();
DateTime sbd = new DateTime();
DateTime tbd = new DateTime();
DateTime fm = new DateTime(now.Year, now.Month, 1);
DateTime sm = new DateTime(now.Year, now.Month, 2);
DateTime tm = new DateTime(now.Year, now.Month, 3);
// first business day
if (fm.DayOfWeek == DayOfWeek.Sunday)
{
fbd = fm.AddDays(1);
}
else if (fm.DayOfWeek == DayOfWeek.Saturday)
{
fbd = fm.AddDays(2);
}
else
{
fbd = fm;
}
//second business day
if (sm.DayOfWeek == DayOfWeek.Sunday)
{
sbd = sm.AddDays(1);
}
else if (sm.DayOfWeek == DayOfWeek.Saturday)
{
sbd = sm.AddDays(2);
}
else
{
sbd = sm;
}
//third business day
if (tm.DayOfWeek == DayOfWeek.Sunday)
{
tbd = tm.AddDays(1);
}
else if (tm.DayOfWeek == DayOfWeek.Saturday)
{
tbd = tm.AddDays(2);
}
else
{
tbd = tm;
}
if (now == fdb || now == sbd || now == tbd)
{
return true;
}
return false;
}
Is this a good approach? How can I add a List<DateTime> with holidays and check that the current date is not holiday?
I have a feeling I'm over thinking this, and thinking it in a bad way. I don't know why but same feeling tells me there is an easier way to do it.
This should do what you want. You'll have to supply the set of holidays.
public static bool IsFirstThreeBusinessDays(DateTime date, HashSet<DateTime> holidays)
{
DateTime dt = new DateTime(date.Year, date.Month, 1);
int businessDaysSeen = 0;
while (businessDaysSeen < 3)
{
if (dt.DayOfWeek != DayOfWeek.Saturday &&
dt.DayOfWeek != DayOfWeek.Sunday &&
!holidays.Contains(dt))
{
if (dt == date.Date)
{
return true;
}
businessDaysSeen++;
}
dt = dt.AddDays(1);
}
return false;
}
You can also do this using LINQ.
public static bool IsFirstThreeBusinessDays(DateTime date, HashSet<DateTime> holidays)
{
var query =
Enumerable.Range(1, DateTime.DaysInMonth(date.Year, date.Month))
.Select(o => new DateTime(date.Year, date.Month, o))
.Where(o => o.DayOfWeek != DayOfWeek.Saturday && o.DayOfWeek != DayOfWeek.Sunday
&& !holidays.Contains(o))
.Take(3);
return query.Contains(date);
}
EDIT: I didn't read the question carefully enough, although parts of my old answer are still applicable. The approach I would take here is to create a method that enumerates the business days of the month, then take 3 from that.
Here's how:
public static IEnumerable<DateTime> BusinessDaysOfMonth(DateTime time)
{
var month = new DateTime(time.Year, time.Month, 1);
var nextMonth = month.AddMonths(1);
var current = month;
while(current < nextMonth)
{
if (IsWeekday(current) && !IsHoliday(current))
{
yield return current;
}
current = current.AddDays(1);
}
}
(note that some methods are taken from below). Then, all you need where you want to use this is:
// Get first three business days
var firstThreeBizDays = BusinessDaysOfMonth(DateTime.Now).Take(3);
// Check if today is one of them
var result = firstThreeBizDays.Contains(DateTime.Today);
OLD ANSWER:
Ok, so it looks like there's three conditions you need to ensure. They are:
It is the 1st, 2nd, or 3rd day of the month
It is not Saturday or Sunday
The current date is not contained in some set of dates representing holidays
This translates fairly straightforwardly to code:
public static bool IsFirstThreeDays(DateTime time) => time.Day < 4;
public static bool IsWeekday(DateTime time)
{
var dow = time.DayOfWeek;
return dow != DayOfWeek.Saturday && dow != DayOfWeek.Sunday;
}
public bool IsHoliday(DateTime time)
{
ISet<DateTime> holidays = ??; // Decide whether this is a member or an arg
return holidays.Contains(time.Date);
}
Note that the holidays set needs to contain the Day component of any DateTime from each holiday.
Now your method is presumably just:
public static bool IsDayWhatYouWant()
{
var now = DateTime.UtcNow;
return IsFirstThreeDays(now) && IsWeekday(now) && !IsHoliday(now);
}
Im trying to perform a check is entered time inside specified time interval but Im stuck... I have one main block and another class which perform the check is the entered time inside the interval but I keep getting "No overload for method 'IsBetween' takes 0 arguments" when I try to call the method and get simple bool true or false, I know that solution is probably really simple but I just cant figure it out... :
static void Main()
{
var currentTime = Console.ReadLine();
DateTime now = Convert.ToDateTime(currentTime);
var dateNow = DateTime.Now;
var startTime = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day, 13, 0, 0);
var endTime = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day, 3, 0, 0);
}
This is my class for check :
public static class TimeExtensions
{
public static bool IsBetween(this DateTime now, DateTime startTime, DateTime endTime)
{
if (now.TimeOfDay == startTime.TimeOfDay) return true;
if (now.TimeOfDay == endTime.TimeOfDay) return true;
if (startTime.TimeOfDay <= endTime.TimeOfDay)
return (now.TimeOfDay >= startTime.TimeOfDay && now.TimeOfDay <= endTime.TimeOfDay);
else
return !(now.TimeOfDay >= endTime.TimeOfDay && now.TimeOfDay <= startTime.TimeOfDay);
}
}
The error suggests you are calling IsBetween like:
bool b = now.IsBetween();
but you need to provide the start and end times:
bool b = now.IsBetween(startTime, endTime);
I need to create a midnight DateTime
I've just done this:
DateTime endTime = DateTime.Now;
endTime.Subtract(endTime.TimeOfDay);
Haven't test it yet, I'm assuming it works but is there a better/cleaner way?
Just use foo.Date, or DateTime.Today for today's date
DateTime endTime = DateTime.Now.Date;
Now endTime.TimeOfDay.ToString() returns "00:00:00"
DateTime.Now . AddDays(1) . Date
DateTime.Today
You can use DateTime.Today with exact seconds of the midnight.
DateTime today = DateTime.Today;
DateTime mid = today.AddDays(1).AddSeconds(-1);
Console.WriteLine(string.Format("Today: {0} , Mid Night: {1}", today.ToString(), mid.ToString()));
Console.ReadLine();
This should print :
Today: 11/24/2016 10:00:00 AM , Mid Night: 11/24/2016 11:59:59 PM
var dateMidnight = DateTime.ParseExact(DateTime.Now.ToString("yyyyMMdd"), "yyyyMMdd", CultureInfo.InvariantCulture);
private bool IsServiceDatabaseProcessReadyToStart()
{
bool isGoodParms = true;
DateTime currentTime = DateTime.Now;
//24 Hour Clock
string[] timeSpan = currentTime.ToString("HH:mm:ss").Split(':');
//Default to Noon
int hr = 12;
int mn = 0;
int sc = 0;
if (!string.IsNullOrEmpty(timeSpan[0]))
{
hr = Convert.ToInt32(timeSpan[0]);
}
else
{
isGoodParms = false;
}
if (!string.IsNullOrEmpty(timeSpan[1]))
{
mn = Convert.ToInt32(timeSpan[1]);
}
else
{
isGoodParms = false;
}
if (!string.IsNullOrEmpty(timeSpan[2]))
{
sc = Convert.ToInt32(timeSpan[2]);
}
else
{
isGoodParms = false;
}
if (isGoodParms == true )
{
TimeSpan currentTimeSpan = new TimeSpan(hr, mn, sc);
TimeSpan minTimeSpan = new TimeSpan(0, 0, 0);
TimeSpan maxTimeSpan = new TimeSpan(0, 04, 59);
if (currentTimeSpan >= minTimeSpan && currentTimeSpan <= maxTimeSpan)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}