calculate time from strings in dropdown lists [duplicate] - c#

This question already has answers here:
Getting time span between two times in C#?
(6 answers)
Closed 7 years ago.
I have 2 dropdown lists holding times in 24 hour format, going up in increments of 5 minutes eg 00:00, 00:05, 00:10. Both lists are displaying strings
When a user selects a start and end time using these, I want to calculate the time difference but I'm not sure how to convert the format I have in the lists to workable times, can anyone help?
Im using C# in Visual Studio 2012.

The code below will show you an example of how to do this:
DateTime d1 = DateTime.Parse("00:00");
DateTime d2 = DateTime.Parse("00:05");
TimeSpan s1 = d2-d1;
Console.WriteLine(s1.TotalMinutes + " minutes difference");
You can replace the strings "00:00", and "00:05" with the values from the dropdown lists, and calculate the timespan between them.

You can use DateTime.ParseExact:
DateTime dt1 = DateTime.ParseExact(ddl1.SelectedValue, "HH:mm",DateTimeFormatInfo.InvariantInfo);
DateTime dt2 = DateTime.ParseExact(ddl2.SelectedValue, "HH:mm",DateTimeFormatInfo.InvariantInfo);
TimeSpan diff = dt2 - dt1;
Now you have all you need in the TimeSpan, f.e.:
int hours = diff.Hours; // 0 - 23
int minutes = diff.Minutes; // 0 - 59
int totalMinutes = (int) diff.TotalMinutes;

Related

C#: Convert 3 Variables into 24 Hours Format

I'm new to C# and i need help on converting 3 int variables into 24 hour format. I look on other Stack Overflow questions but it mostly only convert 1 variable into DateTime meanwhile i need to convert 3 variables into to 24 hour format. Here's what the variable looks like
private int hours = 1;
private int minutes = 1;
private int seconds = 1;
my expected outcome is 01:01:01 but i don't know how to do that.
You can do it like this:
var dt= new DateTime(1, 1, 1, hours, minutes, seconds); // year, month, day, hours, minutes, seconds
If you want to cast to string after that, you can do:
dt.ToString("HH:mm:ss"); // 01:01:01 // 24 hour clock digits
dt.ToString("hh:mm:ss tt"); // 01:01:01 AM // 12 hour clock
I already found a answer that works for me since i can't insert the variables like the previous 2 answers. So i just use
hours.ToString("00")
minutes.ToString("00")
seconds.ToString("00")
this makes it into a string in 2 digit number like my expected outcome.

Calculating for remaining days in current month [duplicate]

This question already has answers here:
How to find the first day of next month,if the current month is december
(12 answers)
Calculate difference between two dates (number of days)?
(17 answers)
Closed 5 years ago.
I would like to know how to calculate the remaining days of the month e.g (15 Feb 2017 to 28 Feb 2017) without the use of a datetimepicker set at 28 Feb 2017.
Here are my codes for subtraction of 2 datetimepicker:
DateTime startDate =
(DateTime)dateTimePicker2.Value;
DateTime endDate =
(DateTime)dateTimePicker1.Value;
TimeSpan ts = endDate.Subtract(startDate);
textBox10.Text = ts.Days.ToString();`
Here are the steps you need to go through:
take your current date
use DateTime.AddMonths() to generate a new date one month from your current date
create a new date that uses 1 for the day, and the month and year from the future date you just worked out
subtract your current date from the future date, this will give you a Timespan which contains the number of days difference
You can use the closely related question Calculate difference between two dates (number of days)? as a guide.
Here is an example, but you can use the Value property from your DateTimePicker instead. DateTime.DaysInMonth(int year, int month) is a helpful method.
DateTime beginDate = new DateTime(2017, 2, 15);
var daysLeft = DateTime.DaysInMonth(beginDate.Year, beginDate.Month) - beginDate.Day;
Console.WriteLine("days from Feb 15 to Feb 28: {0}", daysLeft);
Output:
days from Feb 15 to Feb 28: 13
You can try:
DateTime dt = DateTime.Now;
int days = dt.AddDays(1 - dt.Day).AddMonths(1).AddDays(-1).Day - dt.Day;

How to convert strings to DateTime C# [duplicate]

This question already has answers here:
Parse string to DateTime in C#
(9 answers)
Closed 7 years ago.
I have 3 separate strings with the following format:
01-29-2016: a date, picked from a bootstrap datepicker
1:00am start time, picked from a dropdown, format could also be e.g. 10:00pm
2:30am end time, picked from a dropdown, format could also be e.g. 11:30pm
Using the above strings I need to construct 2 DateTime properties that represent the time range, something like below:
2016-01-29 02:30:00
2016-01-29 01:00:00
I need the DateTime properties so I could update datetime database fields
You can combine both your time parts with date part respectively and use ParseExact method with MM-dd-yyyyH:mmtt format like;
var date = "01-29-2016";
var ts1 = "1:00am";
var ts2 = "2:30am";
var dt1 = DateTime.ParseExact(date + ts1, "MM-dd-yyyyH:mmtt", CultureInfo.InvariantCulture);
// 29.01.2016 01:00:00
var dt2 = DateTime.ParseExact(date + ts2, "MM-dd-yyyyH:mmtt", CultureInfo.InvariantCulture);
// 29.01.2016 02:30:00

Date compare like strtotime in C#? [duplicate]

This question already has answers here:
strtotime equivalent in .NET
(6 answers)
Closed 9 years ago.
Have big problem I don´t know how to compare date in C# like PHP.
I want to convert this code in to C#:
$now = strtotime ("now");
$then = strtotime ("$date");
$difference = $now - $then ;
$num = ($difference/86400)/7;
$weeks = intval($num);
Which function should I use?
This link can´t find a matching function like strtotime.
Please help me to convert the code to C#.
Thanks in advance.
var now = DateTime.Now.TimeOfDay;
DateTime dt = DateTime.Parse(yourDateTime);
var then = dt.ToString("HH:mm");
// here you can do rest of the calculations
basically
dt.ToString("HH:mm"); // 24 hour clock
dt.ToString("hh:mm tt"); // 12 hour clock
Hope it will give you better understanding
I think you might be looking for something like below:
DateTime sDateTimeNow = DateTime.Now;//Gets the date time from the server now
DateTime sIn30Seconds = DateTime.Now.AddSeconds(30);//Gets date time and adds 30 Seconds
DateTime sIn30Hours = DateTime.Now.AddHours(30);//Gets date time and adds 30 hours
DateTime sIn30Days = DateTime.Now.AddDays(30);//Gets date time and adds 30 days
double dTotalDays = (sIn30Days - sDateTimeNow).TotalDays;
double dTotalHours = (sIn30Hours - sDateTimeNow).TotalHours;
double dTotalSeconds = (sIn30Seconds - sDateTimeNow).TotalSeconds;

Exact c# result of sql datediff

I'm trying to get the number of days (calculated byu datediff) in sql and the number of days in c# (calculated by DateTime.now.Substract) to be the same, but they return different results....
//returns 0
int reso = DateTime.Now.Subtract(expirationDate).Days;
vs
//returns 1
dateDiff(dd,getDate(),ExpirationDate)
In both cases, ExpirationDate is '10/1/2011 00:00:00', and the code and the DB are sitting on the same server. I want the return int to be the same. I suspect I'm missing something stupid... ideas??
dateDiff(dd,getDate(),ExpirationDate) Is doing a days comparison. DateTime.Now.Subtract(expirationDate).Days is doing a date and time
For example
SELECT dateDiff(dd,'10/1/2011 23:59:00' , '10/2/2011') returns one day even when only one minute apart.
If you want the same in C# you need to remove the time component
e.g.
DateTime dt1 = new DateTime(2011,10,1, 23,59,0);
DateTime dt2 = new DateTime(2011,10,2, 0,0,0);
Console.WriteLine((int) dt2.Subtract(dt1.Subtract(dt1.TimeOfDay)));
So in your case it would be something like
DateTime CurrentDate = DateTime.Now;
int reso = CurrentDate.Subtract(CurrentDate.TimeOfDay).Subtract(DateTime.expirationDate).Days;
I haven't tested it but I would not do
DateTime.Now.Subtract(DateTime.Now.Subtract.TimeOfDay)
Because the second call to Now wouldn't be guaranteeing to be the same as first call to Now
In any case Stealth Rabbi's answer seems more elegant anyway since you're looking for a TimeSpan not a DateTime
10/1/2011 is less than 1 day away from DateTime.Now. Since you're getting back a TimeSpan and then applying Days to it, you're getting back a TimeSpan that is < 1 day. So it'll return 0 Days.
Instead, just use the Date component of those DateTimes and it'll correctly report the number of days apart - like this:
DateTime now = DateTime.Now;
DateTime tomorrow = new DateTime(2011, 10, 1);
var val = (tomorrow.Date - now.Date).Days;
This will yield you 1 day.
I'm assuming you want the number of Total days, not the number of days from the largest previous unit. You'd want to use the TotalDays property. Also, you may find it easier to use the minus operator to do a subtraction
DateTime d1 = DateTime.Now;
DateTime d2 = new DateTime(2009, 1, 2);
TimeSpan difference = d1 - d2;
Console.WriteLine(difference.TotalDays); // Outputs (today):1001.46817997424

Categories