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"
Related
I have a function which is already compact, i wanted to know if there was better (like a DateTime functionality already included).
Currently i use this:
DateTime today = DateTime.Now;
DateTime tomorrow = new DateTime(today.Year, today.Month, today.Day, 0, 0, 0).AddDays(1);
double remaining = (tomorrow - today).TotalMilliseconds;
Thank for reading.
You can simplify the tomorrow value by just doing this and taking the benefit of DateTime.Today:
DateTime tomorrow = DateTime.Today.AddDays(1);
So your code will be easy to read:
DateTime today = DateTime.Now;
DateTime tomorrow = DateTime.Today.AddDays(1);
double remaining = (tomorrow - today).TotalMilliseconds;
You can create extension for DateTime
public static class DateExtensions
{
public static double GetNextDayRemainingMs(this DateTime dateTime)
{
return (dateTime.AddDays(1).Date - dateTime).TotalMilliseconds;
}
}
Usage
DateTime.Now.GetNextDayRemainingMs();
You can try following code
(DateTime.Today.AddDays(1)-DateTime.Now).TotalMilliseconds
Instead of defining instance for tomorrow variable you can use .AddDate(1).Date property
.AddDate(1) will add one day to DateTime.Now and .Date property
will give you only date and sets time to 00.
DateTime today = DateTime.Now;
double remaining = (today.AddDate(1).Date - today).TotalMilliseconds;
Or (Elegant way)
You can use Today property of DateTime.
An object that is set to today's date, with the time component set to
00:00:00.
double remaining = (DateTime.Today.AddDays(1)-DateTime.Now).TotalMilliseconds
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.
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 ..........
}
I was just wondering if there is a way to get the current time and set it into a value.
If its 12:06 AM.. I want to get that time and set it into currentTime.
Example
float currentTime = 0;
currentTime = 12.06;
As others have mentioned, the DateTime class would be ideal for this, and to work out the difference between 2 date/times:
DateTime end = DateTime.Now;
DateTime start = new DateTime(2011, 12, 5, 12, 6,0);
double hours = (end - start).TotalHours;
The subtraction of DateTime objects results in a TimeSpan object that you can use to see the hours/minutes etc.
try DateTime class
DateTime dt = DateTime.Now;
Is this what you're looking for?
DateTime currentTime;
currentTime = DateTime.Now;
Don't use floats or strings. You can do all kinds of cool things using DateTime.
Here's how you'd get the hours that someone worked:
var clockIn = new DateTime(2011,12,4,9,0,0); // December 4th, 9 AM
var clockOut = new DateTime(2011,12,4,17,0,0); // December 4th, 5 PM
var duration = clockOut - clockIn; // TimeSpan
Console.Write(duration.TotalHours); // 8
A few people have mentioned how, but as a 'better' recommendation you should use
DateTime currentTime = DateTime.UtcNow
Otherwise you have issues when the clocks go back, if your timing code is run on those days. (plus it is far easier to alter the UTC time to local time than it is to convert a '1am' to UTC (as there will be two of them when the clocks go back)
Well if you really what it as a float then try:
var currentDate = DateTime.Now;
float currentTime = float.Parse((currentDate.Hour > 12 ? currentDate.Hour -12 :
currentDate.Hour) + "." + currentDate.Minute);
I wouldn't recommend comparing dates or time with floats. A better options would be to use timespans.
You should be using a Timespan instance for time related values, you can use the flexibility to get the required values like
TimeSpan ts = DateTime.Now.TimeOfDay;
ts.ToString("hh:mm") // this could be what you are looking for
You could then use ts.TotalHours which would give you fractional hours (as a double) else you could construct a string specifically using ts.Hours ..ts.Minutes play around and it could be prove useful.
Try the following:
DateTime StartTime=StartTime value;
DateTime CurrentTime=DateTime.Now;
TimeSpan dt = CurrentTime.Subtract(StartTime);
In dt you will get a working time period.
If you want to have the difference between two times, then do this:
DateTime dateOne = DateTime.Parse(enteredTime);
DateTime dateTwo = DateTime.Now;
TimeSpan difference = dateOne - dateTwo;
I am retrieving data from an iSeries where there is a separate date and time fields. I want to join them into a DateTime field in my C# project. I don't see a way to add just a time to a DateTime field. How would you suggest accomplishing this?
You can do this quite easily:
DateTime dateOnly;
DateTime timeOnly;
...
DateTime combined = dateOnly.Date.Add(timeOnly.TimeOfDay);
TimeOfDay returns a TimeSpan, which you then add to the date.
Edit (thanks to commenters below) - to be safe, use dateOnly.Date to ensure the date part only.
How are they being stored? Assuming that the date portion is being stored as a DateTime of midnight of the day in question and the time is a TimeSpan, you can just add them.
DateTime date = ...;
TimeSpan time = ...;
DateTime result = date + time;
You could easily construct a TimeSpan from your "time" field.
Once you have that, just do:
TimeSpan time = GetTimeFieldData();
dateField = dateField.Add(time);
Datetime date = new DateTime(Date1.Year, Date1.Month, Date1.Day, Time1.Hour, Time1.Minute, Time1.Second);
You can add a TimeSpan to a DateTime and write something like this.
// inside consuming function
ISeriesObject obj = getMyObject();
DateTime dt = getDate(obj) + getTime(obj);
private DateTime getDate(ISeriesObject obj)
{
//return a DateTime
}
private TimeSpan getTime(ISeriesObject obj)
{
//return a TimeSpan
}
My answer addresses joining two objects of DateOnly and TimeOnly in .NET 6:
DateOnly orderDate = ...
TimeOnly orderTime = ...
DateTime orderDateTime = orderDate.ToDateTime(orderTime);
This should do:
var output = date.Date + time.TimeOfDay;
or
var output = new DateTime(date.Year, date.Month, date.Day,
time.Hour, time.Minute, time.Second);
suppose that both variable date and time are both of Type DateTime
Note that adding the time to the date is not your biggest problem here. As #Reed Copsey mentioned, you just create a DateTime from the date and then .Add the time.
However, you need to make sure that the iSeries date and time (a Unix time most probably) are in the same representation as the .Net representation. Thus, you most probably need to convert it by adding it to a Jan 1, 1970 DateTime as well.
Cant you simply format the date part and time part as separate strings, then join them together? Then you can parse the string back to a DateTime object