Calculate how many hours until 8 AM - c#

I know how to calculate the difference between two dates, but how do I calculate the time between a given date and the next 8 AM?

var now = DateTime.Now;
var tomorrow8am = now.AddDays(1).Date.AddHours(8);
double totalHours = ( tomorrow8am - now).TotalHours;

var now = DateTime.Now;
double diffHours = 24 - (now - now.Date).TotalHours + 8;

How about something like this
var now = DateTime.Now();
var target = DateTime.Today.AddDays(1).AddHours(8);
var result = (target - now).Hour;

Works well before 8am the same day.
DateTime now = DateTime.Now;
DateTime next8am =now.Date.AddHours(8);
if(now.TimeOfDay>TimeSpan.FromHours(8))
next8am.AddDays(1);
return next8am.Subtract(now).TotalHours

Related

Get time left until sunday 9:30 pm

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;
}
}

Get time until next occurrence of 6pm?

I've got a thread that is only set to run within a certain period otherwise it's put on delay. From the time of running that threads of a certain Boolean value if true, then it should be delayed by X amount of time from current time to 18:00. Is there a quick way doing this in c#?
DateTime today = DateTime.Now;
DateTime tomorrow = today.Add(new TimeSpan(1,0,0,0));
DateTime tomorrowAtSix = new DateTime(tomorrow.Year, tomorrow.Month, tomorrow.Day, 18,0,0 );
TimeSpan diff = tomorrowAtSix.Subtract(DateTime.Now);
double hoursFromNow = 0d;
double minutesFromNow = 0d;
if(diff.TotalHours > 24d) // next 6pm is tomorrow
{
hoursFromNow = diff.TotalHours - 24d;
minutesFromNow = diff.TotalMinutes - (24d * 60d);
}
else // next 6pm is today
{
hoursFromNow = diff.TotalHours;
minutesFromNow = diff.TotalMinutes;
}
You can subtract DateTime objects which will return a TimeSpan
TimeSpan ts = DateTime.Now - new DateTime(2017, 1, 1);

Time Defferance between two Times in LINQ to Entities?

var TimeNow = DateTime.Now.TimeOfDay;
var qq = from s in _EeHC_HrEntities.TransactionsSecretaries
where (EntityFunctions.CreateTime(s.TransactionTime.Hours,
s.TransactionTime.Minutes,
s.TransactionTime.Seconds) >
EntityFunctions.CreateTime(TimeNow.Hours,
TimeNow.Minutes,
TimeNow.Seconds))
I want compare between two times and display the data that data.time in dataebase > DateTimeNow.time but the result display not True
**becouse th 24 hours convert to 12 hours it will work thanx for answers**
var TimeNow = DateTime.Now.TimeOfDay;
var TimeHourNow = (TimeNow.Hours < 12) ? TimeNow.Hours : (TimeNow.Hours - 12);
var qq = from s in _EeHC_HrEntities.TransactionsSecretaries
where (EntityFunctions.CreateTime(s.TransactionTime.Hours, s.TransactionTime.Minutes, s.TransactionTime.Seconds) > EntityFunctions.CreateTime(TimeHourNow, TimeNow.Minutes, TimeNow.Seconds))

Subtract TimeSpan bigger than 24H

I need to compare two TimeSpan values bigger than 24 hours.
For that I use the following code
string startTime = textBox1.Text;
string endTime = textBox21.Text;
TimeSpan startTimet = new TimeSpan(int.Parse(startTime.Split(':')[0]), // hours
int.Parse(startTime.Split(':')[1]), // minutes
0);
TimeSpan endTimet = new TimeSpan(int.Parse(endTime.Split(':')[0]), // hours
int.Parse(endTime.Split(':')[1]), // minutes
0);
TimeSpan duration = endTimet.Subtract(startTimet);
label29.Text = duration.ToString();
If the values aren't bigger than 24H it's all ok, but if I have a value bigger than 24h the TimeSpan will appear like DD.HH.MM.SS.
For example:
endTimet = 32:15
startTimet = 02:00
duration = 1.06:15:00
And what I really need is the normal format like HH:MM, assuming the hours are greater than 24, getting the expected 30:15
Can anyone help me here?
Regards
Perhaps with this workaround:
TimeSpan duration = TimeSpan.FromHours(30);
string result = string.Format("{0}:{1}"
, duration.TotalHours
, duration.Minutes); // 30:00
Noda Time to the rescue!
string s1 = "123:45";
string s2 = "234:56";
DurationPattern p = DurationPattern.CreateWithInvariantCulture("H:mm");
Duration d1 = p.Parse(s1).Value;
Duration d2 = p.Parse(s2).Value;
Duration diff = d2 - d1;
string result = p.Format(diff); // "111:11"

Setting a DateTime to the first of the next month?

If I have var olddate = DateTime.Parse('05/13/2012');
and I want to get var newdate = (the first of the month after olddate, 06/01/2012 in this case);
What would I code? I tried to set the month+1 but month has no setter.
Try this:
olddate = olddate.AddMonths(1);
DateTime newDate = new DateTime(olddate.Year, olddate.Month, 1,
0, 0, 0, olddate.Kind);
This won't ever cause out-of-range errors, and will preserve the DateTime's Kind.
dt = dt.AddMonths(1.0);
dt = new DateTime(dt.Year, dt.Month, 1, 0, 0, 0, dt.Kind);
You have to define the Month and Year rightly, and after set the 1ยช day. Try this:
// define the right month and year of next month.
var tempDate = oldDate.AddMonths(1);
// define the newDate with the nextmonth and set the day as the first day :)
var newDate = new DateTime(tempDate.Year, tempDate.Month, 1); //create
Try this simple one-liner:
var olddate = DateTime.Parse("05/13/2012");
var newdate = olddate.AddDays(-olddate.Day + 1).AddMonths(1);
// newdate == DateTime.Parse("06/01/2012")
lots of examples...pick your posion ;)
var olddate = DateTime.Parse("05/12/2012");
int currentDay = ((DateTime)olddate).Day;
//can always replace the while loop and just put a 1 for current day
while(currentDay != 1)
currentDay--;
var newdate = (DateTime.Parse(olddate.AddMonths(1).Month.ToString() + "/" + currentDay.ToString() + "/" + olddate.AddMonths(1).Year.ToString()));

Categories