How to calculate hours between 2 different dates in c# - c#

I have been building a program where i need to calculate the difference between different dates....... its a network outage program i want to calculate down time between different dates e.g network was down on 08/06/2013 9:00 AM and was restored on 09/06/2013 10:00 PM.... the down time should be 34 hours......... i have been able to calculate the days but i want this in hour format so anyone please help me.............
i m using datetimePicker to get the date and time at the same time.
i have been using the below mentioned code for that purpose
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = " dd/MM/yyyy hh:mm tt ";
dateTimePicker2.Format = DateTimePickerFormat.Custom;
dateTimePicker2.CustomFormat = " dd/MM/yyyy hh:mm tt ";
ts1 = dt2.Subtract(dt1);
richTextBox1.Text = "The Hours Difference is:\t" + dt2.Subtract(dt1).Hours + "\n The Minute Difference is:\t" + dt2.Subtract(dt1).Minutes;

You can use the .Net timespan class for this.
System.DateTime firstDate = new System.DateTime(2006, 9, 13, 12, 0, 0);
System.DateTime SecondDate = new System.DateTime(2006, 9, 13, 0, 0, 0);
System.TimeSpan diffResult = firstDate.Subtract(SecondDate);
diffResult will contain all the differences in firstDate and secondDate in year, month, day, hour, minutes and seconds.
You can get any datepart from this:
diffResult.Days
diffResult.Hours
diffResult.Minutes
etc.

You need
dt2.Subtract(dt1).TotalHours
and
dt2.Subtract(dt1).TotalMinutes

Related

Insert time without the date into my database

I tried to insert into my MS Access database a specific format to see how just the "time" in my database behaves, but when I tried to show what I got the date also, but I want to insert just the time.
I tried to convert the datetime variable to specific format and insert that
DateTime starttime = Convert.ToDateTime(DateTime.Now.ToShortTimeString());
DateTime nstarttime = Convert.ToDateTime(starttime.ToString("HH:mm"));
06/04/2019 22:55:00 that what I got and I want just the time
without the date
Your main issue is, that in .Net the time part of a DateTime is not a DateTime but a TimeSpan:
DateTime dateTime = new DateTime(2019, 6, 4, 22, 55, 0);
TimeSpan timePart = dateTime.TimeOfDay;
In Access (VBA) however, a "time only" value is the time of the date of the VBA Date epoch which is 1899-12-30. Depending on how you insert the time in an Access table, you may have to apply the time part to the epoch to obtain a value like that Access would use:
DateTime dateTime = new DateTime(2019, 6, 4, 22, 55, 0);
TimeSpan timePart = dateTime.TimeOfDay;
DateTime vbaEpoch = new DateTime(1899, 12, 30);
DateTime vbaTime = vbaEpoch.AddTicks(timePart.Ticks);
Of course, when reading back the values, ignore the date part:
TimeSpan timeOfDay = vbaTime.TimeOfDay;
This has been answered so many times, but nevertheless here is the link to one of the discussions Link 1:
Please check also this Link 2 with may useful patterns
This detail is one of the actual examples provided on Link 1:
DateTime dt = DateTime.Parse("6/22/2009 07:00:00 AM");
dt.ToString("HH:mm"); // 07:00 // 24 hour clock // hour is always 2 digits
dt.ToString("hh:mm tt"); // 07:00 AM // 12 hour clock // hour is always 2 digits
dt.ToString("H:mm"); // 7:00 // 24 hour clock
dt.ToString("h:mm tt"); // 7:00 AM // 12 hour clock
Hope this helps!
Cheers and happy coding!

Customer date start time

When my application starts I have a datetimepicker for a start time and end time.
dvSubmittedDateBegin.Format = DateTimePickerFormat.Custom;
dvSubmittedDateBegin.CustomFormat = "MMM dd yyyy - hh mm tt";
Everything works. However I've been asked to have the start default default at 5AM.
I created a new datetime and assigned the dvSubmittedDateBegin.Value - dt;
However the new datetime I guess I have to specify every int?
DateTime dt = new DateTime(2015, 6, 24, 05, 00, 0);
What happens tomorrow when its 6/25? Not sure how to fix this.
How about like;
DateTime dt = DateTime.Today + TimeSpan.FromHours(5);
or more simple
DateTime dt = DateTime.Today.AddHours(5);
You will get the current date from midnight with DateTime.Today and you will add 5 hours to it and it will be 5 AM of the current day.
You can use the AddDays(), AddHours(), AddMinutes() etc. methods:
DateTime dt = DateTime.Today.AddHours(5);
You can create a function that would return a particular date where you pass all the components and define time components as default parameters:
DateTime CreateDateWith5amStart(int year, int month, int day, int hour = 5, int minute = 0, int second = 0)
{
return new DateTime(year, month, day, hour, minute, second)
}
If they provide only date components, it will set time to 5 a.m. If they need a different time, they can provide time components.

How to find overlapping hours of a timerange and a date range?

I have a time range 11:00 PM to 5:00 AM. (night hours range)
I have date range for eg.,
2014-04-01 00:00:00 to 2014-04-02 23:59:59
Now I need to calculate how many night hours are present in the given date range.
For the above example it should return 11 hours 59 minutes 59 seconds
Explanation:
2014-04-01 00:00 AM to 2014-04-01 5:00 AM = 5 hours
2014-04-01 11:00 PM to 2014-04-02 5:00 AM = 6 hours
2014-04-02 11:00 PM to 2014-04-02 11:59:59 PM = 0 hour 59 minutes 59 seconds
one second approximation is okay.
If these are strings, you need to parse them to DateTime with DateTime.ParseExact method and then get difference them with - operator. This gets you a TimeSpan. I see your strings have different formats. You need to parse them matched format one by one.
After that, you can use TimeSpan properties like;
string s = "2014-04-01 00:00 AM";
var date = DateTime.ParseExact(s,
"yyyy-MM-dd HH:mm tt",
CultureInfo.InvariantCulture);
string s1 = "2014-04-01 5:00 AM";
var date1 = DateTime.ParseExact(s1,
"yyyy-MM-dd H:mm tt",
CultureInfo.InvariantCulture);
TimeSpan ts = date1 - date;
Console.WriteLine(string.Format(#"{0} hours {1} minutes {2} seconds",
ts.Hours, ts.Minutes, ts.Seconds));
Output will be;
5 hours 0 minutes 0 seconds
If they are already DateTime, just use - operator and use .Hours, .Minutes and .Seconds properties of TimeSpan structure.
There is a project called Calculating Business Hours which is calculate business hours between two DateTime. You can implement your own night shift hours based this project.
You can use the CalendarPeriodCollector of the Time Period Library for .NET:
// ----------------------------------------------------------------------
public void NightHours()
{
CalendarPeriodCollectorFilter filter = new CalendarPeriodCollectorFilter();
filter.CollectingHours.Add( new HourRange( 0, 5 ) ); // working hours
filter.CollectingHours.Add( new HourRange( 23, 24 ) ); // working hours
CalendarTimeRange testPeriod =
new CalendarTimeRange( new DateTime( 2014, 4, 1 ),
new DateTime( 2014, 4, 3 ) );
Console.WriteLine( "Calendar period collector of period: " + testPeriod );
CalendarPeriodCollector collector =
new CalendarPeriodCollector( filter, testPeriod );
collector.CollectHours();
Console.WriteLine( "Duration: " + new DateDiff( collector.Periods.TotalDuration ) );
} // NightHours

Subtract time from date using format string

If I have a date and time in a DateTime object, can I remove say 10 minutes, or 24 hours etc from the date and time using a format string?
So if I have 1/1/1990 12:30:00pm and I wanted to remove 1 hour from it, can I use a format string?
edit
i need to store diary entries and the user can select a reminder type. so 1 hour before hand. so then i'd like to store the format string in a db that i can get and apply to a datetime to get the reminder date time
Something like this might do what you need. Not sure what you mean by subtracting an hour using a format string though.
DateTime dt = new DateTime(1990, 1, 1, 12, 30, 0);
string s = dt.Subtract(new TimeSpan(1, 0, 0)).ToString("MM/dd/yyyy hh:mm:ss tt")
Best way is to convert to a DateTime object and then back to the formatted string (if that's what you need):
var time = DateTime.Parse("1/1/1990 12:30:00pm");
time = time.AddMinutes(-10);
string timeString = time.ToString("MM/dd/yyyy hh:mm:ss tt");
You can use this in your query if you have..
DATE_SUB(date,INTERVAL expr unit)
Example:
YourDate = DATE_SUB(1/1/1990 12:30:00pm, INTERVAL 1 HOUR)
YourDate = DATE_SUB(1/1/1990 12:30:00pm, INTERVAL 12 MINUTE)
YourDate = DATE_SUB(1/1/1990 12:30:00pm, INTERVAL 45 SECONDS)

Get user input, convert the data and then output it into a text box

I'm trying to compile my first C# application (based on Visual Studio) ... also using Windows Forms for input (from user) and output.
User puts numbers into six text boxes (e.g. 2009 20 02 02:49:35) and then when the 'Convert' button is clicked, the program outputs E1234FB3278DC0 in a different text box.
Not sure if this is relevant but E1234FB3278DC0 = 63370694975000000 (in decimal).
oh also, I'm not sure about convertedText.writeline... should it be this.textBox7 = microseconds; ?
String dateString = yyyy.Text + dd.Text + mm.Text + hh.Text + mm.Text + ss.Text;
DateTime timestamp = DateTime.ParseExact(dateString, "yyyy dd mm hh:mm:ss", CultureInfo.CurrentCulture);
long ticks = timestamp.Ticks;
long microseconds = ticks / 10;
convertedText.WriteLine(microseconds.ToString("X"));
Thanks in advance..
And I gotta thank Luxspes for the orginal version.
Some tips about this code snippet.
String dateString = yyyy.Text + dd.Text + mm.Text + hh.Text + mm.Text + ss.Text;
DateTime timestamp = DateTime.ParseExact(dateString, "yyyy dd mm hh:mm:ss", CultureInfo.CurrentCulture);
First of all, it's really strange that you use the same "mm"-object for months and minutes. The same problem with format specifier. To parse month you should use 'M'.
long ticks = timestamp.Ticks;
long microseconds = ticks / 10;
convertedText.WriteLine(microseconds.ToString("X"));
So, if your date parsed successfully you'll get the number of microseconds that have elapsed since 12:00:00 midnight, January 1, 0001. It's E1234FB3278DC0 in hexadecimal (for the date in your question).
But in your case date represented in the seconds. So, the number of microseconds will be always.
timestamp.Millisecond*1000;
I have no idea about the type of convertedText object. But it seems to me that's not a problem.
Try to use the following code:
String dateString = yyyy.Text+dd.Text+M.Text+hh.Text+mm.Text+ss.Text;
DateTime dateTime = DateTime.ParseExact(dateString, "yyyy dd M hh:mm:ss", CultureInfo.CurrentCulture);
long microseconds = dateTime.Ticks/10;
convertedText.Text = microseconds.ToString("X");

Categories