How to get Difference between SelectStartDate to SelectEndDate on monthcalender in C# - c#

I m trying to get date count from month calender on C# .my code like this
leave.Amount = Convert.ToInt32((mclDateRange.SelectionEnd - mclDateRange.SelectionStart).TotalDays.ToString());
I got error like this
Input string was not in a correct format.

TimeSpan.TotalDays property is of type double, you can get the integer part like:
leave.Amount = (int) (mclDateRange.SelectionEnd - mclDateRange.SelectionStart).TotalDays;
Consider the following example:
double d = 123.22d;
int number = Convert.ToInt32(d.ToString());
The would result into the exception
Input string was not in a correct format.
So in your code, you can leave out the call ToString and it would be fine, like:
leave.Amount =
Convert.ToInt32(
(mclDateRange.SelectionEnd - mclDateRange.SelectionStart).TotalDays);

Here’s a step by step example on how to diff two datetime objects. Just apply this to your code
DateTime startDate = DateTime.Parse("01/01/2013");
DateTime endDate = DateTime.Parse("05/22/2013");
TimeSpan dateDiff = endDate.Subtract(startDate);
int dayDiff = dateDiff.Days;
If you want to round fractional days (like 4 days 18 hrs) days to the nearest one (5 in this case) then use TotalDays property and convert to Int.

This is the way i did for datetimepicker hope it will work to monthcalender
DateTime dt;
DateTime Todate ,FromDate;
Todate = DateTime.ParseExact(datetimepicker1.Value.Date.ToString("dd/MM/yyyy"), "dd/MM/yyyy", CultureInfo.InvariantCulture);
FromDate = DateTime.ParseExact(datetimepicker2.Value.Date.ToString("dd/MM/yyyy"), "dd/MM/yyyy", CultureInfo.InvariantCulture);
double datedifference = (Todate - FromDate).TotalDays;
Then can check as date checking like this
if(datedifference <2)
{
something ..........
}

Related

Compare dateTime "MM/dd/yyyy hh:mm:ss" with "yyyy-MM-dd hh:mm:ss" in c# LINQ

How to check dateTime greater than with below format date Time.
In "CreatedDate" column have below format values.
Created Date
2020-03-01 10:59:50.250
2020-03-01 10:40:39.610
2020-03-01 10:39:18.087
2020-02-29 07:39:18.087
public IQueryable<UserProfile> GetTopUserProfiles(System.DateTime startDateTime)
{
return GetDbContext(toUpdate).Get<UserProfile>( w =>w.CreatedDate >= startDateTime);
}
var dtstart = DateTime.Now.ToString("yyyy-MM-dd");
statDateTime = Convert.ToDateTime(dtstart).AddHours(8); //add 8 hours to current date.
//start DateTime value: 3/1/2020 8:00:00 AM
var count = _userProfileRepository.Value.GetTopUserProfiles(startDate).Count();
count is returning 0.
Expected count is 3
Basically, You no need to convert to yyyy-MM-dd.
You should consider whether the server time value between .NET back-end and SQL Database is the same or not.
Try below code
return GetDbContext(toUpdate).Get<UserProfile>( w => DateTime.Compare(w.CreatedDate,startDateTime) > 0);

DateTime representation and conversion shows the wrong date

I am trying to create a new date from parameters that I receive from a request.
I have this code:
DateTime datefrom = DateTime.ParseExact(DateFromTextBox1.Text,"dd/mm/yyyy", CultureInfo.InvariantCulture).ToUniversalTime();
int hoursFrom = HourFromTextBox1.Text!=String.Empty?Convert.ToInt32(HourFromTextBox1.Text):0;
int minutesFrom = HourFromTextBox1.Text != String.Empty ? Convert.ToInt32(MinuteFromTextBox1.Text) : 0;
date1 = new DateTime(datefrom.Year, datefrom.Month, datefrom.Day, hoursFrom, minutesFrom, 0).ToString("yyyy-MM-dd HH:mm:ss");
I get something like this:
2018-01-19 13:11:00
When the initial date that I tried to parse was this:
"20/10/2018"
The hours and minutes are correct. But the day and month are not.
I think the output is because the time on my computer is something like this:
11-Oct-18. This may be a cultural problem.
How can I get the correct date from what is expected?
Converting time to Universal Time making the result differ. Try "dd/MM/yyyy" as parse string. "mm" is used for minutes in datetime parsing refer this documentation for datetime custom formats Custom Date and Time Format Strings
Ex -
DateTime datefrom = DateTime.ParseExact("20/10/2018","dd/MM/yyyy", CultureInfo.InvariantCulture);
Console.WriteLine(datefrom); //20.10.2018 00:00:00 without universal time
DateTime datefromUniversal = DateTime.ParseExact("20/10/2018","dd/MM/yyyy", CultureInfo.InvariantCulture).ToUniversalTime();
Console.WriteLine(datefromUniversal); //19.10.2018 22:00:00 with universal time
int hoursFrom = "13"!=String.Empty?Convert.ToInt32("13"):0;
int minutesFrom = "11" != String.Empty ? Convert.ToInt32("11") : 0;
var date1 = new DateTime(datefrom.Year, datefrom.Month, datefrom.Day, hoursFrom, minutesFrom, 0).ToString("yyyy-MM-dd HH:mm:ss");
Console.WriteLine(date1);
Hope now you understood

Calculating the Number of Days between two Dates and displaying it in a Label

Hi I'm trying to capture two dates selected by the user in a C# Calendar Control and I want the date range to be displayed in a label. I have worked out on the following code but it generates a Minus value ; not the actual date range.
DateTime from = CalFrom.SelectedDate;
DateTime to = CalTo.SelectedDate;
double days = (CalTo.SelectedDate - CalFrom.SelectedDate).TotalDays;
TimeSpan t = to - from;
double noOfDays = t.TotalDays;
TimeSpan ts = to - from;
double differnceindays = ts.TotalDays;
lblNoofDays.Text = differnceindays.ToString();
This code is working perfectly for me for calculating the number the days between two days.
DateTime d1 = DateTime.Now;
DateTime d2 = DateTime.Now.AddDays(10);
TimeSpan difference = d2 - d1;
var days = difference.TotalDays;
DateTime.Now.Subtract(startDate).Days.ToString();
try to calculate no of days between two dates
string days = (date2 - date1).Value.Days.ToString();
The only problem I see is that you assume the start and end dates will be correctly range checked, meaning start date is never greater than end date (which would produce negative values for total days). If you want to correct for the fact that start date may be after end date, then this should work.
DateTime startDate = DateTime.Now.AddDays(-94); // Example random 94 day span..
DateTime endDate = DateTime.Now;
TimeSpan duration = endDate > startDate ? endDate - startDate : startDate - endDate;
double daysBetweenDates = duration.TotalDays;
Note: "daysBetweenDates" will include fractional days (thus the double type). Also, the code above assumes local time. If you want UTC you will need to account for that.

String To DateFormat Conversion

Is there any way I don't have to specify the number of digits in day/month/year?
For e.g 1/2/1991
I want a method which satisfies both 1/2/1991,11/3/1990,12/12/1991
I don't know how many digits will be there in either month, year, or days.
My code is
string copy = splittedData[0] + splittedData[1] + splittedData[2];//date+month+year
DateTime datetime = DateTime.ParseExact(copy, "ddMMyyyy", CultureInfo.InvariantCulture);
DateTime dateAndTime = datetime;
The problem is the number of digits in splitted data array are not known to me and thus the above format "ddMMyyyy" give me exception on some cases.
Since you already have the day month and year then just create a date with the three of them like so;
DateTime date = new DateTime(year, month, day);
No parsing is necessary. You already have all the fields you want to create the date, and you dont need to put it into a special format to create a date.
If you are not sure the if the input is valid, then wrap the creation in a try/catch block to catch an ArgumentOutOfRangeException should it should occur.
Since you updated your question with the code you have, you can concatenate date components with a separator like:
string copy = splittedData[0] + "/" + splittedData[1] + "/" + splittedData[2];
Later you can do:
DateTime dt = DateTime.ParseExact(copy, "d/M/yyyy", CultureInfo.InvariantCulture);
I used the format "d/M/yyyy" with single d and M which would account for both single/double digit day/month.
So it will work for dates like:
01/01/2013
1/01/2013
22/09/2013
02/9/2013
DateTime.ParseExact is specifically intended to not allow what you are asking for. DateTime.Parse will allow it, though.
You say you have the 3 parts as separate strings -- if you insert the /'s and parse, it should succeed (InvariantCulture expects the order month-day-year):
string datetimeString = string.Join("/", new[] {month, day, year});
DateTime datetime = DateTime.Parse(datetimeString, CultureInfo.InvariantCulture);
Or you could convert them to integers and construct a DateTime directly:
DateTime datetime = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), Convert.ToInt32(day));
What #n00b said. You've already got the individual components of the date: why are you globbing them back together just so you can call DateTime parsing routines? Just do something like this:
private static DateTime StringToDateTime( string year , string month , string day )
{
int yyyy = int.Parse(year) ;
int mm = int.Parse(month) ;
int dd = int.Parse(day) ;
DateTime dt = new DateTime(yyyy,mm,dd) ;
return dt ;
}
As an added bonus, The above code will probably run faster than DateTime.Parse() or DateTime.ParseExact().

DateTime calculation

I have been getting an annoying issues. I have two datetime variables. Date of employment and termination date. I need to get the number of days work. termindation date - date of employment.
how do i go about getting this?
DateTime empDate = int.Parse((employeeEmploy.ElementAt(i).dateofEmpl).GetValueOrDefault().ToString("yyyyMMdd"));
DateTime terminDate = int.Parse((employeeEmploy.ElementAt(i).terminDate ).GetValueOrDefault().ToString("yyyyMMdd"));
int? dWorked = terminDate - empDate;
I tried that but that didnt work
Well, you're trying to deal with DateTime values - so you shouldn't be using int.Parse to start with. Use DateTime.ParseExact. Once you've got two DateTime values, you can use subtraction to get a TimeSpan, and then compute the total days from that:
DateTime employmentDate = ...;
DateTime terminationDate = ...;
TimeSpan employmentDuration = terminationDate - employmentDate;
int days = (int) employmentDuration.TotalDays;
Personally I'd actually use my Noda Time project to do all of this, mind you:
private static LocalDatePattern TextPattern =
LocalDatePattern.CreateWithInvariantInfo("yyyyMMdd");
...
LocalDate employmentDate = TextPattern.Parse(...).Value;
LocalDate terminationDate = TextPattern.Parse(...).Value;
int days = Period.Between(employmentDate, terminationDate, PeriodUnits.Days)
.Days;
Subtracting DateTime objects produces TimeSpan. So, use TimeSpan.TotalDays to get total days count between two dates:
int dWorked = (terminDate - empDate).TotalDays;
UPDATE: For LINQ to Enitites use EntityFunctions.DiffDays method, which calculates days between two nullable dates:
from x in context.Foo
select EntityFunctions.DiffDays(x.FromDate, x.ToDate)
try something along the lines of
var numDays = (terminDate - empDate ).TotalDays;
dworked = (int)Math.Round(numDays, MidpointRounding.AwayFromZero);
You can easily substract the two Datetimes which gets you a TimeSpan!
DateTime employmentDate = new DateTime(2013,03,8);
DateTime terminationDate = new DateTime(2013,03,11);
TimeSpan days = terminationDate - employmentDate;
Console.WriteLine("Days: " + days.TotalDays); //Result: "Days: 3"

Categories

Resources