can anyone help me with the formatting of the following?
if(system.datetime.now > 20:00:00 AND < 23:59:59)
NewDateTime = (system.datetime.now + 1 day) + time as 00:01:00
ie if the sysdate meets the criteria, make NewDateTime = Sysdate + 1 day, with the time as 00:01:00
thanks
You shouldn't be dealing with formatting at all here. I suspect you want something like:
TimeSpan earliest = new TimeSpan(20, 0, 0);
TimeSpan latest = new TimeSpan(23, 59, 59);
DateTime now = DateTime.Now;
TimeSpan currentTime = now.TimeOfDay;
if (currentTime > earliest && currentTime < latest)
{
DateTime newDateTime = now.Date.AddDays(1).AddHours(1);
}
One important point here is that I'm only taking DateTime.Now once, rather than every time we're interested in "the current time". That leads to better consistency.
I'd also question your "latest" part - do you really want the behaviour to be different at 23:59:59.5? Don't you really mean "any time after 8pm"? And possibly that should be inclusive, too? That would lead to:
// Probably make this a static readonly field
TimeSpan earliest = new TimeSpan(20, 0, 0);
DateTime now = DateTime.Now;
TimeSpan currentTime = now.TimeOfDay;
if (currentTime >= earliest)
{
DateTime newDateTime = now.Date.AddDays(1).AddHours(1);
}
DateTime now = DateTime.Now;
DateTime newDateTime;
if (now.Hours >= 20)
{
newDateTime = now.Date.AddDays(1).AddHours(1);
}
Roughly this is what I think you want:
CurrentTime=DateTime.Now;
if(CurrentTime.GetHour()>19)
{
NewDateTime=CurrentTime.AddDays(1);
NewDateTime.SetHour(1);
NewDateTime.SetMinute(0);
NewDateTime.SetSecond(0);
}
I think you can do that - if not you can calculate the time based on the current time
NewDateTime.AddHours(-CurrentTime.Hour-1)
NewDateTime.AddMinutes(-CurrentTime.Minute);
Your code is not valid in many aspects:
if(system.datetime.now > 20:00:00 AND < 23:59:59)
In C#, there is no "between" operator, so you need two comparisons plus the AND:
if(system.datetime.now > 20:00:00 AND system.datetime.now < 23:59:59)
It is && (for or, it is ||)
if(system.datetime.now > 20:00:00 && system.datetime.now < 23:59:59)
Note that && and || have short-circuit behaviour, that is, if the left operand of && if false, the right operand is not evaluated. Same for ||, except that if the left hand operand is true, the right hand operand is not evaluated.
C# does not have time literals. Now it depends on what exactly you want to compare. Do you intend to see whether it is 20 o'clock already? Then do (note that DateTime.Now also contains today's date, DateTime.Today is the beginning of the current day):
if(system.datetime.now > system.datetime.today.addHours (20)
&& system.datetime.now < system.datetime.today.addDays (1))
C# source code is case sensitive, so
if(System.DateTime.Now > System.Datetime.Today.AddHours (20)
&& System.DateTime.Now < System.DateTime.Today.AddDays (1))
You could also work with TimeSpans, which comes in handy when you also want to specify minutes and seconds (assume 20:15 for example):
if(System.DateTime.Now > System.Datetime.Today.Add (new TimeSpan(20,15,0))
&& System.DateTime.Now < System.DateTime.Today.AddDays (1))
I'd advise to use a named value, though:
var tomorrow = System.DateTime.Today.AddDays(1);
var quincyTime = today.Add (new TimeSpan (20,15,0));
if(System.DateTime.Now > quincyTime && System.DateTime.Now < tomorrow)
Further, which is important, Now gives you (roughly) the moment when you call it. So if you have multiple invocations of Now, store it so it doesn't change throughout the execution of your function:
var now = System.DateTime.Now;
var today = System.DateTime.Today;
var quincyTime = today.Add (new TimeSpan (20,15,0));
var tomorrow = today.AddDays(1);
if(now > quincyTime && now < tomorrow)
The observing reader might recognize that not even Today might be save if this program runs in a nuclear power plant at midnight. There is cure:
var now = System.DateTime.Now;
var today = now.Date;
Also note that the if-body is either a single statement, e.g.
if(now > quincyTime && now < tomorrow)
; // empty statement
if(now > quincyTime && now < tomorrow)
foobar();
or a whole "block":
if(now > quincyTime && now < tomorrow)
{
} // empty block
if(now > quincyTime && now < tomorrow)
{
foobar();
frob();
}
Btw, if you meant "at least"/"at max" instead of "later"/"sooner", use <= and >=:
if(now >= quincyTime && now <= tomorrow) {...}
Related
This question already has answers here:
Find if current time falls in a time range
(12 answers)
Closed 4 years ago.
I'm attempting to write my first C# script. The script is for opening hours... My if ((weekDay == sunday) && time > openingTime && closingTime < time) line is spitting errors due to:
CS0019 C# Operator '<' cannot be applied to operands of type 'string' and 'int'
After looking at related answers on SO, I still haven't been able to get my code working. I've tried converting the string into an int, this didn't work (unless I did something stupid)
var weekDay = DateTime.Today.DayOfWeek;
var isOpen = "We are open!";
var isClosed = "We are closed";
var sunday = DayOfWeek.Sunday;
var time = DateTime.Now.ToString("hh:mm");
var openingTime = 08;
var closingTime = 16;
if ((weekDay == sunday) && time > openingTime && time < closingTime)
{
Console.WriteLine(isClosed);
}
You can use DateTime struct insted of string and use its properties like Hour to retrieve current hour.
var time = DateTime.Now;
if ((time.DayOfWeek == sunday) && time.Hour > openingTime && closingTime < time.Hour)
{
Console.WriteLine(isClosed);
}
This is a more structured way to solve a problem then convert DateTime to string and then parse the string back to extract current hour.
It seems that you want to evaluate against the current hour. Use the DateTime.Hour property instead, you cannot do the comparison between an int and a string.
var weekDay = DateTime.Today.DayOfWeek;
var isOpen = "We are open!";
var isClosed = "We are closed";
var sunday = DayOfWeek.Sunday;
var time = DateTime.Now.Hour;
var openingTime = 8;
var closingTime = 16;
if ((weekDay == sunday) && time > openingTime && time < closingTime)
{
Console.WriteLine(isClosed);
}
I am to fill a ddl at run time.
What I actually need to do is pick up the current time from the system (in 24-hour format).
Then I need to round it up to a 15 min slot, so if the time is 13:23 it will become 13:30; if it is 13:12 then it should become 13:15.
Then I want to add 45 minutes to it, and 13:15 becomes 14:00.
I am trying to achieve it like this
DateTime d = DateTime.Now;
string hr = d.ToString("HH:mm");
string mi = d.ToString("mm");
Could somebody tell, either I have to write all logic or DateTime can provide some feature
to format it like this?
I think this should do the trick for you:
var d = DateTime.Now;
d = d.AddSeconds(-d.Seconds).AddMilliseconds(-d.Milliseconds)
if (d.Minute < 15) { d.AddMinutes(15 - d.Minute); }
else if (d.Minute < 30) { d = d.AddMinutes(30 - d.Minute); }
else if (d.Minute < 45) { d = d.AddMinutes(45 - d.Minute); }
else if (d.Minute < 60) { d = d.AddMinutes(60 - d.Minute); }
d = d.AddMinutes(45);
DateTime d = DateTime.Now;
//Add your 45 minutes
d = d.AddMinutes(45);
//Add minutes to the next quarter of an hour
d = d.AddMinutes((15 - d.TimeOfDay.Minutes % 15) % 15);
//Show your result
string hr = d.ToString("HH:mm");
string mi = d.ToString("mm");
DateTime in C# has a function for adding any increment to the current DateTime object. Here is a reference to the specific function for minutes.
DateTime d = DateTime.Now;
DateTime rounded;
if(d.Minute % 15 ==0)rounded = d;
else DateTime rounded = d.AddMinutes(15 - d.Minute % 15);
Console.WriteLine("{0:HH:mm}",rounded);
I have a function which takes two DateTime parameters and I have to add separate offsets to these date. I know that DateTime has a AddDays function to add days to a date and it throws an exception if DateTime is less than MinValue or greater than MaxValue.
Now I want to do a safe check whether adding/subtracting the following number of days to a DateTime can cause over/under flow or not.
safeStartDate = (startDate == DateTime.MinValue || startDate == DateTime.MaxValue) ? startDate : startDate.AddDays(startDateOffset);
safeEndDate = (endDate == DateTime.MaxValue || endDate == DateTime.MinValue) ? endDate : endDate.AddDays(enDateOffset);
By doing this, I am making it one level exception free but date can be DateTime.Max - 1 and while trying to add offset it throws an exception. I am looking a better way that whether the final values over/under flows without doing the actual calculation, in order to prevent exception.
If catch is not called very often you can do:
try
{
safeDate = dt.AddDays(days);
}
catch (ArgumentOutOfRangeException)
{
safeDate = date;
}
Alternatively,
var maxDays = (DateTime.MaxValue - dt).TotalDays;
safeDate = (days <= maxDays) ? dt.AddDays(days) : dt;
Or if there are negative days:
var maxDays = (DateTime.MaxValue - dt).TotalDays;
var minDays = (DateTime.MinValue - dt).TotalDays;
return (minDays <= days && days <= maxDays) ? dt.AddDays(days) : dt;
Or just use the method from Rawling's answer: CanAddDays(dt, days) ? dt.AddDays(days) : dt
The try/catch version is about 25% faster if you don't catch and about 1000x slower if you do. So, if you expected to catch more than about 1 time in every 5000 uses, then use the second version.
You can use the following to check whether you can add a given number of days to a given DateTime without causing an overflow:
bool CanAddDays(DateTime dt, int days)
{
double maxDaysToAdd = (DateTime.MaxValue - dt).TotalDays;
double minDaysToAdd = (DateTime.MinValue - dt).TotalDays;
return days <= maxDaysToAdd && days >= minDaysToAdd;
}
You might consider the following method:
private static DateTime AddDays(DateTime dateTime, int days)
{
var daysTimeSpanTicks = (new TimeSpan(days, 0, 0, 0)).Ticks;
return (days >= 0) ?
(DateTime.MaxValue.Ticks < dateTime.Ticks + daysTimeSpanTicks) ? dateTime : dateTime.AddDays(days) :
(dateTime.Ticks + daysTimeSpanTicks < 0) ? dateTime : dateTime.AddDays(days);
}
A sample usage is:
DateTime date = DateTime.MinValue;
DateTime safe = AddDays(date, -100);
I guess you are looking for something like this
DateTime Now = DateTime.Now;
DateTime Max = DateTime.MaxValue;
Max.Subtract(Now);
int DaysToAdd = 1000;//or something else
if (Max.Day > DaysToAdd) Now.AddDays(DaysToAdd);//add
I have a IQueryable<Journey> that i collect from my entity model. I want to use this to get a new set of IQueryable<Journey> but only within a specific date interval from 2 textboxes on my webpage.
A Journey has Journey.DateFrom and Journey.DateTo which are strings ("YYYYMMDD").
I thought i would do something like this:
(journeys is IQueryable<Journey>)
if (tb_DateFrom.Text != ""){
journeys = from j in journeys
where Convert.ToInt32(j.DateTo) >= Convert.ToInt32(tb_DateFrom.Text)
select j;
}
if (tb_DateTo.Text != ""){
journeys = from j in journeys
where Convert.ToInt32(j.DateFrom) <= Convert.ToInt32(tb_DateTo.Text)
select j;
}
But i get error saying that linq doesnt know how to do Convert.ToInt32, neither does it know how to do int.parse or datetime.parse. What works is to use IEnumerable<Journey> instead of IQueryable<Journey> but that is so slow that the website crash since the data im comparing is quite huge.
How can i work this out, is the only answer to get the format in db to datetime?
Please help :)
I'd try this:
if (tb_DateFrom.Text != "") {
journeys = from j in journeys
where j.DateTo.CompareTo(tb_DateFrom.Text) >= 0
select j;
}
if (tb_DateTo.Text != "") {
journeys = from j in journeys
where j.DateFrom.CompareTo(tb_DateTo.Text) <= 0
select j;
}
Why don't you convert textbox values to datetime and then compare the dates in the where clause, instead of converting to int
DateTime? dateFrom = null, dateTo = null;
if(!String.IsNullOrWhiteSpace(tb_DateFrom.Text))
dateFrom = DateTime.ParseExact(tb_DateFrom.Text, "yyyyMMdd", null);
if (!String.IsNullOrWhiteSpace(tb_DateTo.Text))
dateTo = DateTime.ParseExact(tb_DateTo.Text, "yyyyMMdd", null);
if (dateFrom.HasValue)
journeys = journeys.Where(j => j.DateFrom >= dateFrom.Value);
if (dateTo.HasValue)
journeys = journeys.Where(j => j.DateTo <= dateTo.Value);
private DateTime getDate(string yyyyMmDd, DateTime defaultValue)
{
DateTime ret = DateTime.MinValue;
if (!DateTime.TryParse(yyyyMmDd, out ret))
return defaultValue;
return ret;
}
var to = DateTime.Parse(tb_DateTo.Text);
var from = DateTime.Parse(tb_DateFrom.Text);
journeys.Where(j=> getDate(j.DateFrom, DateTime.MaxValue) <= from && getDate(j.DateTo, DateTime.MinValue) >= to);
As the string format you have sorts in the same order as the dates they represent, I don't see why you have to convert their data format at all. Just do (untested):
journeys = from j in journeys
where j.DateTo >= tb_DateFrom.Text && j.DateFrom >= tb_DateTo.Text
select j;
Update, after Joakim's comment, still just using the sort order of the strings:
journeys = from j in journeys
where j.DateTo.CompareTo(tb_DateFrom.Text) >= 0 &&
j.DateFrom.CompareTo(tb_DateTo.Text) <= 0
select j;
(Det borde väl fungera, Joakim?)
Oops, I missed the accepted answer, but I'll still leave my first edit...
how to find whether the sunday falls between two dates.if sunday exist subtract one days from the difference between two days
If I understand correctly, you are looking for something like this:
public static bool DoesIncludeSunday(DateTime startDate, DateTime endDate)
{
bool r = false;
TimeSpan testSpan = new TimeSpan(6, 0, 0, 0);
TimeSpan actualSpan =endDate - startDate;
if (actualSpan >= testSpan) { r = true; }
else
{
DateTime checkDate = endDate;
while (checkDate > startDate)
{
r = (checkDate.DayOfWeek == DayOfWeek.Sunday);
if(r) { break; }
checkDate = checkDate.AddDays(-1);
}
}
return r;
}
The endDate needs to be the most recent date. The first part simply keeps us from checking if the start and end dates are more than 6 days apart (it will include a sunday, so no need to continue). The second bit just walks backward one day at a time from the endDate checking if Sunday is in there.
Once you know if sunday is part of the span, you can make whatever changes to the dates you want from the calling code.
Just because I like to be clever, I wrote it up this way:
public static int DaysExcludingSundays(DateTime start, DateTime end)
{
return ((end - start).Days + 1) - ((((end - start).Days + 1) + (((int)start.DayOfWeek + 6) % 7)) / 7);
}
Feel free to copy and paste this code without understanding what it means. I enjoyed the puzzle.
Broken down:
int startOffset = ((int) start.DayOfWeek + 6) % 7;
int totalInclusiveDays = (end - start).Days + 1;
int numberOfSundays = (totalInclusiveDays + startOffset) / 7;
int numberOfDaysWithoutSundays = totalInclusiveDays - numberOfSundays;