Calculate Time Difference, and using Days - c#

Okay i got a way to calculate the time Difference between 2 files, or rather 2 "dates".
And it works, however, if the time difference is a day, meaning one starts at, let´s say 23:00, and the other 01:20 the next day, it will fail and think it´s behind rather than just 2 hours in front.
Here is the code:
private void button1_Click(object sender, EventArgs e)
{
try
{
DateTime firstDt;
DateTime lastDt;
if (DateTime.TryParseExact(First.Text, "yyyy-MM-dd HH-mm-ss-fff", CultureInfo.InvariantCulture, DateTimeStyles.None, out firstDt)
&& DateTime.TryParseExact(Last.Text, "yyyy-MM-dd HH-mm-ss-fff", CultureInfo.InvariantCulture, DateTimeStyles.None, out lastDt))
{
var difference = lastDt.TimeOfDay - firstDt.TimeOfDay;
Console.WriteLine(difference);
CalcDiff.Text = "DelayAudio(" + difference.TotalSeconds.ToString("F3") + ")";
}
}
catch (Exception ex)
{
MessageBox.Show("TimeSpan Calculate: " + ex.Message);
}
}
Not really sure how to make it use the Day, as it seems like it should do it.

Just perform the subtraction on the full dates (rather than their time components):
var difference = lastDt - firstDt;

You can use the TimeSpan class to do that. For so, you need to substract a Date from another, like
TimeSpan ts = lastDate - startDate;
Console.Write(ts.Hours + ":" + ts.Minutes + ":" + ts.Seconds); // ts.ToString("HH:mm:ss") should work.

DateTime firstDt;
DateTime lastDt;
DateTime.TryParse(First.Text, out firstDt);
DateTime.TryParse(Last.Text, out lastDt);
TimeSpan difference = lastDt - firstDt;
CalcDiff.Text = "DelayAudio(" + difference.ToString()+ ")";

Related

Change the time forward

I am getting dates from the database and for each date I want to change the time forward starting from the DateTime that was obtained from the database until I get to a given Fixed Time (Y). However, (Y) might be in the next day.
For example if the date from the database is [7/6/2017 5:00:00 AM] and the given Fixed Time is 10:00 PM then I want to get [7/6/2017 10:00:00 PM].
However if the fixed time is 02:00 AM then I want to get [7/7/2017 02:00:00 AM] (notice that the date has increased by one)
Note: The code is running, but I modified the code to make it shorter and make more sense. Thus, there might be syntax or spelling mistakes.
My first solution was something like this:
private DateTime setTimeForeward(DateTime date) {
DateTime today = DateTime.ParseExact(FixedTime, "hh:mm tt", CultureInfo.InvariantCulture);
TimeSpan difference = today.TimeOfDay - date.TimeOfDay;
return date + difference;
}
That didn't work as expected when the fixed time is 02:00 AM. The difference becomes negative( it doesn't go around the clock) and the date will be [7/6/2017 02:00:00 AM].
I ended up with the following code
private DateTime setTimeForeward(DateTime date) {
DateTime today = DateTime.ParseExact(FixedTime "hh:mm tt", CultureInfo.InvariantCulture);
TimeSpan difference = today.TimeOfDay - date.TimeOfDay;
if (difference.Hours < 0) {
difference += new TimeSpan(24, 0, 0);
}
return date + difference;
}
I am not sure if my function is logically correct and I feel like I am overthinking it. Also,I am not sure if there's a better way or a built in function that does what I want for me. Basically, I am looking for a correct and an elegant solution.
Thank you very much in advanced.
In this method, I'm using DateTime fixedTime to represent a time. I don't really care about it's Day, Month, and Year values.
static DateTime GetClosingTime(DateTime fixedTime, DateTime dbTime)
{
var cutoff = new DateTime(dbTime.Year, dbTime.Month, dbTime.Day, fixedTime.Hour, fixedTime.Minute, fixedTime.Second);
if (dbTime < cutoff)
return cutoff;
else
{
cutoff = cutoff.AddDays(1);
return cutoff;
}
}
Here's calling it with your provided example input.
var FixedTime10PM = new DateTime(1, 1, 1, 22, 0, 0);
var FixedTime02AM = new DateTime(1, 1, 1, 2, 0, 0);
var dbTime = new DateTime(2018, 6, 20, 5, 0, 0);
var dt1 = GetClosingTime(FixedTime10PM, dbTime);
var dt2 = GetClosingTime(FixedTime02AM, dbTime);
Console.WriteLine(dt1.ToLongDateString() + " " + dt1.ToLongTimeString());
Console.WriteLine(dt2.ToLongDateString() + " " + dt2.ToLongTimeString());
And here's my output:
EDIT:
Simplified method based on suggestions in comments:
static DateTime GetClosingTime(DateTime fixedTime, DateTime dbTime)
{
var cutoff = new DateTime(dbTime.Year, dbTime.Month, dbTime.Day, fixedTime.Hour, fixedTime.Minute, fixedTime.Second);
return dbTime < cutoff ? cutoff : cutoff.AddDays(1);
}
Your logic is almost right but you shouldn't be checking for difference.Hours because there might be a difference in minutes (or even seconds if you changed the format later).
I adjusted your function and changed some variable names to make them easier to follow:
private DateTime SetTimeForward(DateTime originalDate)
{
TimeSpan newTime = DateTime.ParseExact(FixedTime,
"hh:mm tt",
CultureInfo.InvariantCulture).TimeOfDay;
TimeSpan diff = newTime - originalDate.TimeOfDay;
if (diff.Ticks < 0)
diff = diff.Add(new TimeSpan(24, 0, 0));
return originalDate.Add(diff);
}
Some remarks:
If your FixedTime is really fixed, you might want to store it directly as a TimeSpan so you don't have to parse it every time.
If you parse the FixedTime because it's changeable, you might pass it as a second argument instead:
private DateTime SetTimeForward(DateTime originalDate, string fixedTime)
Or:
private DateTime SetTimeForward(DateTime originalDate, TimeSpan newTime)
The current implementation does not change the date value if the newTime is equal to originalDate.TimeOfDay. I.E., If the originalDate is 7/6/2017 2:00 AM and the FixedTime/newTime is 02:00 AM, the returned date will be equal to the originalDate. If that's not your desired behavior, you might change diff.Ticks < 0 to diff.Ticks <= 0.
Slightly different approach:
private DateTime setTimeForeward(DateTime date)
{
var targetTimeOfDay = TimeSpan.ParseExact(FixedTime, "hh:mm tt", CultureInfo.InvariantCulture);
if (targetTimeOfDay < date.TimeOfDay)
{
date = date.AddDays(1);
}
return date.Date + targetTimeOfDay;
}
I'm getting target time as TimeSpan from the beginning instead of creating DateTime and getting TimeOfDay (which is TimeSpan).
Then I check if the target time of day is lower than time to be modified and if it is I add one day.
I use date.Date + targetTimeOfDay as return value as date.Date will return date with time set to 00:00 and adding target time to it will already set the target hour without calculating the difference.

dateTimePicker1.Value < dateTimePicker2.Value = true when values are identical on runtime

I have dateTimePicker1 and dateTimePicker2 controls loading on Form1. They both have the same date and time on load.
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "yyyy-MM-dd hh:mm:ss";
dateTimePicker2.Format = DateTimePickerFormat.Custom;
dateTimePicker2.CustomFormat = "yyyy-MM-dd hh:mm:ss"
When I check if they have different values using
if (dateTimePicker1.Value < dateTimePicker2.Value) {
Console.WriteLine(dateTimePicker1.Value + " is earlier than " + dateTimePicker2.Value);
}
the statement returns true and writes to the console. This is not what I would expect. I would expect this to return false.
If I increase each control's value by 1 second, causing them to still match, the statement returns false as expected and nothing is written to the console.
Why does the less than evaluation return true on load when both values are identical?
Do not know how you are loading the values. But, depending on what precision you are looking for (eg. in hours, minutes or second) you can subtract the two values and compare. Example: If you need precision in seconds then you can do something similar to below:
dateTimePicker1.Value = DateTime.Now;
dateTimePicker2.Value = DateTime.Now.AddMilliseconds(999);
var timeSpan1 = dateTimePicker1.Value - dateTimePicker2.Value;
if (Math.Abs(timeSpan1.TotalSeconds) > 1) {
MessageBox.Show(dateTimePicker1.Value + " is not same as " + dateTimePicker2.Value);
} else {
MessageBox.Show(dateTimePicker1.Value + " is same as " + dateTimePicker2.Value);
}
The answer is given by setting the two values equal to each other on load. This is because the controls load at different times. They are not really equal.
private void Form1_Load(object sender, EventArgs e)
{
dateTimePicker2.Value = dateTimePicker1.Value;
}
I'm not sure how to give credit here, it belongs to two commenters.

Label Display Integer

I'm making a alarm clock in my application and the code requires me to set a variable int from a combo box into my program.
if ((e.Result.Text == "set a alarm") || (e.Result.Text == "set an alarm"))
{
Jarvis.Speak("setting alarm");
label2.Content = DateTime.Today.Hour.ToString(HourAlarmCB) + ":" + DateTime.Today.Minute.ToString("54") + ":" + DateTime.Today.Second.ToString("00");
label2.Opacity = 100;
dispatcherTimer2.Start();
}
The HourAlarmCB is the ComboBox with content in it "1","2", etc. but the error wont allow me to use ToString, is there any way around this?
I believe that you may be incorrectly making use of ToString().
Are you trying to retrieve the following formatted result?
hh:mm:ss
If so, you might find this approach worthy of consideration:
int hour = Convert.ToInt32(HourAlarmCB.SelectedItem);
int minute = DateTime.Today.Minute;
int second = DateTime.Today.Second;
label2.Content = String.Format("{0:D2}:{1:D2}:{2:D2}", hour, minute, second);
See String.Format for converting an arbitrary list of variables into a single formatted string.
For a description of "D2", see Standard Numeric Format Strings.
Update: First, note that DateTime.Today returns "an object that is set to today's date, with the time component set to 00:00:00."
Now, in reference to your question, to output AM or PM, use the t standard format string:
DateTime date = DateTime.Today; // time is '00:00:00'
int hour = Convert.ToInt32(HourAlarmCB.SelectedItem);
int minute = date.Minute; // always '0'
int second = date.Second; // always '0'
label2.Content = String.Format("{0:D2}:{1:D2}:{2:D2} {3:t}",
hour, minute, second, date); // for example: '08:00:00 AM'
So the end result is me having to the HourAlarmCB variable to a string
if ((e.Result.Text == "set a alarm") || (e.Result.Text == "set an alarm"))
{
Jarvis.Speak("setting alarm");
string HourAlarmStr = HourAlarmCB.SelectedItem.ToString();
label2.Content = DateTime.Today.Hour.ToString(HourAlarmStr) + ":" + DateTime.Today.Minute.ToString("54") + ":" + DateTime.Today.Second.ToString("00");
label2.Opacity = 100;
dispatcherTimer2.Start();
}

Set datetimepicker value using hour and minute int Variables

got a problem.
I want to convert two doubles to a time format (HH:mm)(2.5 equals to 02:30 for example). I got a hour int variable and minute int variable. The problem is that I don't know what to do with them, I mean how I import them to the date time picker.
At the beginning the time is stored in a string in an array.
public {
int hour = 5;
int min =40;
time.Value = new DateTime(hour, min);// ***this is a mistake***
}
The outcome should be 05:40 in a datepicker
not sure about your requirement, but something like below,
time.Value = DateTime.Today.AddHours(hours).AddMinutes(minutes);
Figured out the answer.
DetaTimePicker.Value = new DateTime(DateTime.Now.Year, DateTime.Now.Month,
DateTime.Now.Day, hour integer, minute integer, 0);
The zero is the minutes.
Thanks guys.
SET time as 13:30
DateTimePicker newDate = (DateTimePicker)rootcontrol;
String format = "H:mm";
DateTime dDate;
try
{
DateTime.TryParseExact(answer, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dDate);
newDate.Format = DateTimePickerFormat.Custom;
newDate.Value = dDate;
}
catch (System.ArgumentOutOfRangeException)
{
newDate.Text = answer;
Console.WriteLine("ERROR SET TIME:" + answer);
}

Calculate time difference in c# windows phone 7

I am trying to calculate the time difference between 2 time and put the result into a text block.
For example,
Start time: 9:45 AM
End start: 5:15 PM
How can i calulate the time difference between it?
DateTime dt1 = DateTime.ParseExact(DateTime.Now.ToShortTimeString(), "hh:mm tt", new DateTimeFormatInfo());
DateTime dt2 = DateTime.ParseExact(timePicker1.ValueString, "hh:mm tt", new DateTimeFormatInfo());
TimeSpan ts1 = dt2.Subtract(dt1);
For time "11:12 PM" you should use format "h:mm tt". So, you parse two time strings and make Subtract or just (dateTime1 - dateTime2).
try:
DateTime dt1 = DateTime.ParseExact("22:22:22", "HH:mm:ss", new DateTimeFormatInfo());
DateTime dt2 = DateTime.ParseExact("11:11:11", "HH:mm:ss", new DateTimeFormatInfo());
TimeSpan ts1 = dt1.Subtract(dt2);
protected void Page_Load(object sender, EventArgs e)
{
// Declare and get DateTime values
DateTime StartDate = System.DateTime.Now;
DateTime EndDate = System.DateTime.UtcNow;
// Find time difference between two dates
TimeSpan TimeDifference = StartDate - EndDate;
// Write difference in hours and minutes
Response.Write("Time difference between server time and Coordinated Universal Time (UTC) is " +
TimeDifference.Hours.ToString() + " hours ");
if (TimeDifference.Minutes != 0)
Response.Write(" and " + TimeDifference.Minutes.ToString() + " minutes.");
}
or try
/* Read the initial time. */
DateTime startTime = DateTime.Now;
Console.WriteLine(startTime);
/* Do something that takes up some time. For example sleep for 1.7 seconds. */
Thread.Sleep(1700);
/* Read the end time. */
DateTime stopTime = DateTime.Now;
Console.WriteLine(stopTime);
/* Compute the duration between the initial and the end time.
* Print out the number of elapsed hours, minutes, seconds and milliseconds. */
TimeSpan duration = stopTime - startTime;
Console.WriteLine("hours:" + duration.Hours);
Console.WriteLine("minutes:" + duration.Minutes);
Console.WriteLine("seconds:" + duration.Seconds);
Console.WriteLine("milliseconds:" + duration.Milliseconds);
The method suggested by O.D. is what I use in my app that uses a time difference. I then use the method ng_ducnghia suggests to separate units of time (hours, min, sec - I don't need millisec for my purpose).

Categories

Resources