Subtracting timespan from 24 hours - c#

I'm trying to subtract my potentially negative timespan values from 24 hours to change them into positive values.
As an example case:
I want to find how much time is there till 8:00 AM.
If it's 16:00 PM now, timespan gives me -8 ish value so I want to substract it from 24 to get 16.
I'm trying this but it's giving me this error
The DateTime represented by the string is not supported in calendar
System.Globalization.GregorianCalendar.
What I tried ;
string startTime = String.Format("{0:t}", "8:00");
TimeSpan timeLeft = Convert.ToDateTime(startTime).Subtract(DateTime.Now);
if (timeLeft.TotalMinutes < 0 )
{
timeLeft = Convert.ToDateTime(String.Format("{0:H}","24:00")).Subtract(Convert.ToDateTime(timeLeft.Negate())) ;
}
How can I achieve subtracting my potentially negative timespans from 24 hours?

You are confusing TimeSpan and DateTime. I guess there is an easier way:
var eightOClock = TimeSpan.FromHours(8);
var now = DateTime.Now;
var till8again = now.TimeOfDay > eightOClock
? TimeSpan.FromHours(32) - now.TimeOfDay
: eightOClock - now.TimeOfDay;
So if TimeOfDay is less than eight hours (it's before 8am), we take the difference to 8am. If it's greater than 8am, we take the difference to 32hours, which is 8am tomorrow.

A DateTime is an absolute date, happening at a certain day, month, year... It must not be used to represent a specific hour.
So your attempt to convert "8:00", or "24:00" in a DateTime will forcibly fail.
For this you must use TimeSpan (or eventually an integer if you always work with hours).
You can use for example
if(DateTime.Now.TimeOfDay > TimeSpan.FromHours(8))
To see if it's more or less than 8:00.
TimeOfDay will return you the amount of time elapsed for today since midnight.
DateTime has also a lot of useful methods to Add or Substract time, see https://msdn.microsoft.com/fr-fr/library/system.datetime(v=vs.110).aspx for details

Use TimeSpan, and if the startDate is less the Now, add a day to it and then make the comparison.
TimeSpan startTime = new TimeSpan(8,0,0);
TimeSpan now = DateTime.Now.TimeOfDay;
startTime = startTime < now ? startTime.Add(TimeSpan.FromDays(1)) : startTime;
TimeSpan diff = startTime - now;

Another point: the error is coming from the fact that 24:00 doesn't represent 12:00 midnight. 0:00 represents midnight, and that will be a valid DateTime.

Related

Compare two DateTimes with ignoring seconds and milliseconds

I take two object from database. One is a filename with date init and second one is a DateTime object like 2021-08-08 17:32:07.880.
First, I converted filename to datetime with the code shown here:
var fileDate = DateTime.ParseExact(filename, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
I have to check that the difference between the first date and the second date is 3 hours 15 min or simply 3 hours.
How do I delete seconds and milliseconds of date 2, and compare them?
I'd go similar to MatJ's recommendation:
You've got your file time, and your DB time, which might have seconds and milliseconds on it. If you do the later one minus the earlier one you get a timespan representing the length of time between the datetimes
dBDate - fileDate
Timespans have a TotalMinutes property that is a decimal. A timespan of 5 minutes 45 seconds would have a TotalMinutes of 5.75
So, if we cast that to an int it cuts off the seconds; simples!
var t = (int)((dBDate - fileDate).TotalMinutes);
Now you can compare your t for equality to 180 (3h) or 195 (3h15h
It is very easy to do !
Try following code :
TimeSpan timeSpan = (firstDate - secondDate)
timeSpan.CompareTo(new TimeSpan(3, 15, 0)) // hrs, mins, seconds
This CompareTo method will return 1 if difference between two times is greater than 3 hrs and 15 mins, otherwise, it will return -1
PS:
firstDate and secondDate are in DateTime

C# - Compute total hours between 8:00 to 2:00 AND 8:00 to 12:00

Here's my code
DateTime TimeIn = "8:00 AM",
TimeOut="2:00 AM";
double Total;
private void compute()
{
Total = (TimeOut - TimeIn).TotalHours;
}
8:00am to 2:00am should result 18 hours.But mine is resulting -7
Another problem is when i typed 24:00 as time out C# couldn't recognize it as Time.
It works properly when the TimeOout is less than 12:00am. like 11:59pm backwards.
(eg.: 11:30PM - 8:00AM) it computes properly.
Please Help.
Add +24 hours when negative result.
may be this could help you:
string TimeIn= "8:00 AM";
string TimeOut= "2:00 AM";
TimeSpan duration = DateTime.Parse(TimeOut).Subtract(DateTime.Parse(TimeIn));
The way you have declared the datetime Value is wrong. The right way to do it is by converting the string to datetime format
DateTime TimeIn = Convert.ToDateTime("08:00");
DateTime TimeOut = Convert.ToDateTime("02:00");
TimeSpan ts = TimeIn - TimeOut;
If you need the 18 hours span that you're looking for you'll have to pass the date value as well while assigning data to the variables

how to convert 24-hour format TimeSpan to 12-hour format TimeSpan?

I have TimeSpan data represented as 24-hour format, such as 14:00:00, I wanna convert it to 12-hour format, 2:00 PM, I googled and found something related in stackoverflow and msdn, but didn't solve this problem, can anyone help me? Thanks in advance.
Update
Seems that it's possible to convert 24-hour format TimeSpan to String, but impossible to convert the string to 12-hour format TimeSpan :(
But I still got SO MANY good answers, thanks!
(Summing up my scattered comments in a single answer.)
First you need to understand that TimeSpan represents a time interval. This time interval is internally represented as a count of ticks an not the string 14:00:00 nor the string 2:00 PM. Only when you convert the TimeSpan to a string does it make sense to talk about the two different string representations. Switching from one representation to another does not alter or convert the tick count stored in the TimeSpan.
Writing time as 2:00 PM instead of 14:00:00 is about date/time formatting and culture. This is all handled by the DateTime class.
However, even though TimeSpan represents a time interval it is quite suitable for representing the time of day (DateTime.TimeOfDay returns a TimeSpan). So it is not unreasonable to use it for that purpose.
To perform the formatting described you need to either rely on the formatting logic of DateTime or simply create your own formatting code.
Using DateTime:
var dateTime = new DateTime(timeSpan.Ticks); // Date part is 01-01-0001
var formattedTime = dateTime.ToString("h:mm tt", CultureInfo.InvariantCulture);
The format specifiers using in ToString are documented on the Custom Date and Time Format Strings page on MSDN. It is important to specify a CultureInfo that uses the desired AM/PM designator. Otherwise the tt format specifier may be replaced by the empty string.
Using custom formatting:
var hours = timeSpan.Hours;
var minutes = timeSpan.Minutes;
var amPmDesignator = "AM";
if (hours == 0)
hours = 12;
else if (hours == 12)
amPmDesignator = "PM";
else if (hours > 12) {
hours -= 12;
amPmDesignator = "PM";
}
var formattedTime =
String.Format("{0}:{1:00} {2}", hours, minutes, amPmDesignator);
Admittedly this solution is quite a bit more complex than the first method.
TimeSpan represents a time interval not a time of day. The DateTime structure is more likely what you're looking for.
You need to convert the TimeSpan to a DateTime object first, then use whatever DateTime format you need:
var t = DateTime.Now.TimeOfDay;
Console.WriteLine(new DateTime(t.Ticks).ToString("hh:mm:ss tt"));
ToShortTimeString() would also work, but it's regional-settings dependent so it would not display correctly (or correctly, depending on how you see it) on non-US systems.
TimeSpan represents a time interval (a difference between times),
not a date or a time, so it makes little sense to define it in 24 or 12h format. I assume that you actually want a DateTime.
For example 2 PM of today:
TimeSpan ts = TimeSpan.FromHours(14);
DateTime dt = DateTime.Today.Add(ts);
Then you can format that date as you want:
String formatted = String.Format("{0:d/M/yyyy hh:mm:ss}", dt); // "12.4.1012 02:00:00" - german (de-DE)
http://msdn.microsoft.com/en-us/library/az4se3k1%28v=vs.100%29.aspx
Try This Code:
int timezone = 0;
This string gives 12-hours format
string time = DateTime.Now.AddHours(-timezone).ToString("hh:mm:ss tt");
This string gives 24-hours format
string time = DateTime.Now.AddHours(-timezone).ToString("HH:mm:ss tt");
Assuming you are staying in a 24 hour range, you can achieve what you want by subtracting the negative TimeSpan from Today's DateTime (or any date for that matter), then strip the date portion:
DateTime dt = DateTime.Today;
dt.Subtract(-TimeSpan.FromHours(14)).ToShortTimeString();
Yields:
2:00 PM
String formatted = yourDateTimeValue.ToString("hh:mm:ss tt");
It is very simple,
Let's suppose we have an object ts of TimesSpan :
TimeSpan ts = new TimeSpan();
and suppose it contains some value like 14:00:00
Now first convert this into a string and then in DateTime
as following:
TimeSpan ts = new TimeSpan(); // this is object of TimeSpan and Suppose it contains
// value 14:00:00
string tIme = ts.ToString(); // here we convert ts into String and Store in Temprary
// String variable.
DateTime TheTime = new DateTime(); // Creating the object of DateTime;
TheTime = Convert.ToDateTime(tIme); // now converting our temporary string into DateTime;
Console.WriteLine(TheTime.ToString(hh:mm:ss tt));
this will show the Result as: 02:00:00 PM
Normal Datetime can be converted in either 24 or 12 hours format.
For 24 hours format - MM/dd/yyyy HH:mm:ss tt
For 12 hours format - MM/dd/yyyy hh:mm:ss tt
There is a difference of captial and small H.
dateTimeValue.ToString(format, CultureInfo.InvariantCulture);

How to get the time difference between two DateTime objects?

emp = moduleEmployee.ReturnEmployeeDAO().FetchEmployeeByID(emp);
DateTime shiftStartTime = emp.Shift.StartTime;
DateTime shiftEndTime = emp.Shift.EndTime;
DateTime attTime = att.Time;
According to the above code my shiftStartTime is 11.00 PM and shiftEndTime is 7.00 AM. and attTime or signIntime is 1.00 AM. then how to calculate the difference between shiftStartTime and attTime. where the difference should be 2 hour.
please help.....
Thanks Rusho
If you subtract two DateTime objects, you get a TimeSpan.
A TimeSpan then has properties for TotalMilliseconds, TotalSeconds, etc.
You want the TimeSpan.TotalHours
int shiftHours = (attTime - shiftStartTime).TotalHours;
Just subtract one time from the other and you'll get a TimeSpan object.
see http://msdn.microsoft.com/en-us/library/1905yhe2.aspx
TimeSpan diff = att.Time.Subtract(emp.Shift.StartTime);
are you asking for something like this: ?
var timeSpan = (attTime - shiftStartTime);
the result is a TimeSpan where you can check how many hours, minutes, days, seconds and so on...

Time Math Guidance needed

I have a DateTime object that is 10:00 AM
This time represents what time of day a report should be run.
I want to calculate the amount of time remaining from NOW until 10:00 AM
part of my confusion is NOW might be after 10:am or BEFORE 10am,
I keep playing around with TimeSpan, but my results are not quite right... I am sure this is simple, but it is one of those things I have been working of for a few hours and I need a push in the right direction...
I want the timespan object timeTillRun to be correct...here is what I have tried:
{
DateTime scheduledRun = DateTime.Today.AddHours(_timeToStart);//_timeToStart = 10
TimeSpan timeTillRun = DateTime.Now - scheduledRun;
}
This will work... but you need to reverse the order of subtraction:
TimeSpan timeTillRun = scheduledRun - DateTime.Now;
Note that if it's currently after 10AM, timeTillRun will be negative. You will presumably also need to check if the current time is on or after 10AM, then add 10 hours and one day to DateTime.Today to obtain the next run time. Alternatively, you could test if timeTillRun is negative; if so, just add one day to it (timeTillRun += new TimeSpan(1, 0, 0, 0)).
Try this
DateTime timeToStart = DateTime.Today.AddHours(10);
TimeSpan timeTillRun;
// Checking to see if current time is passed schedule run, if it is then we add a day (this is assuming this is run daily, if days are skipped like weekends for example then this would need some tweaking)
if (DateTime.Now > timeToStart)
timeTillRun = DateTime.Now.AddDays(1.0) - timeToStart;
else
timeTillRun = DateTime.Today - timeToStart;
double totalHoursRemaining = timeTillRun.TotalHours; // get total hours remaining
string prettyRemaining = String.Format("{0} day and {1} hours", timeTillRun.Days, timeTillRun.Hours); // can do some outputting here

Categories