Calculating dates expecting double - c#

I am trying to simply subtract two dates. Probably this is a messy way of doing it. It says it cannot convert to double even though.
DateTime daysPlus14days = _dal.getOptinDate(new Guid(_myuser.id.ToString())).AddDays(14);
DateTime currentDate = DateTime.Now;
DateTime timeLeft = (daysPlus14days - currentDate).TotalDays
This just basically goes to db and gets me the date they created there account. Its just to work out how many days left they have 14 days to click a button other wise it will vanish.
public DateTime getOptinDate(Guid id)
{
var q = _dal.portalEntities.tblPortalUsers.Where(a => a.id == id).FirstOrDefault();
return (DateTime)q.optinDateStart;
}

just change this line:
double timeLeft = (daysPlus14days - currentDate).TotalDays;
TotalDays returns double and not DateTime

Refer this link https://msdn.microsoft.com/en-us/library/system.timespan.totaldays(v=vs.110).aspx,
System.DateTime date1 = new System.DateTime(1996, 6, 3, 22, 15, 0);
System.DateTime date2 = new System.DateTime(1996, 12, 6, 13, 2, 0);
System.TimeSpan diff1 = date2.Subtract(date1);
double totaldays = diff1.TotalDays;

Related

Days between two dates in asp.net

I find the number of days between the date of the employee's employment and the date of the day, and multiply by the daily amount. The only complaint is that when I find out the number of days between two dates, it calculates over 31 days for the months that draw 31 days naturally. I need to trade over 30 days while I get the dates between two dates.
How can I do that?
Do you want something like this?
DateTime date1 = new DateTime(2016, 10, 3);
DateTime date2 = new DateTime(2016, 11, 3);
var numberOfDays = date2.Subtract(date1).TotalDays;
I Hope this is what you wanted:
DateTime firstDay = DateTime.ParseExact("2016-10-03", "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
DateTime lastDate = DateTime.ParseExact("2016-11-03", "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
double daysBetween = (lastDate - firstDay).TotalDays;
if you are just interested in full month, you can use following code
var normalisedDays = ((lastDate.Year - firstDate.Year) * 12 + lastDate.Month - firstDate.Month) * 30;
in Controll :
DateTime Date_1 = Date_Start;
DateTime Date_2 = Date_End;
TimeSpan difference = Date_2 - Date_1 ;
var days = difference.TotalDays;
in Script :
<script>
function calculateDifference()
{
var Date_Start= document.getElementById("Date_Start").value;
var Date_End= document.getElementById("Date_End").value;
var Date_StartSplit = Date_Start.split("/");
var Date_EndSplit = Date_End.split("/");
var StartDate = new Date(Date_StartSplit[2], Date_StartSplit[0] - 1, Date_StartSplit[1]);
var EndDate = new Date(Date_EndSplit[2], Date_EndSplit[0] - 1, Date_EndSplit[1]);
var res = Math.abs(StartDate - EndDate) / 1000;
var days = Math.floor(res / 86400);
document.getElementById("Nombre_days").value = days;
}
</script>

How do I change the date only in a C# DateTime object

I am looking for a elegant solution (if it exists) to achieve what I described in the title.
I saw an elegant solution for "changing the time in a DateTime object" and it is as follows:
DateTime s = ...;
TimeSpan ts = new TimeSpan(10, 30, 0);
s = s.Date + ts;
If there such a solution for changing the date in a DateTime object?
DateTime struct is designed to be immutable, so you can't change it. You can get a new one based on values from the old one, which is exactly what your solution does.
You can make it a bit more clear by using DateTime constructor which takes all date and time values: year, month, day, hour, minute and seconds.
s = new DateTime(s.Year, s.Month, s.Day, 10, 30, 0);
s = new DateTime(2014, 10, 2, s.Hour, s.Minute, s.Second);
or you can use TimeOfDay property:
s = new DateTime(2014, 10, 2) + s.TimeOfDay;
Assuming that you are going to pass a new DateTime object to update your existing object, a function like this can work.
DateTime UpdateDate(DateTime existingDate, DateTime newDate)
{
return newDate.Date + existingDate.TimeOfDay;
}
myDatetime = new DateTime(year, month, day);
You can use the DateTime constructors, so you can preserve the original time.
See this example:
var firstDate = new DateTime(2015, 01, 01, 15, 0, 0);
var newDate = DateTime.Now;
// New date, original time.
firstDate = new DateTime(newDate.Year, newDate.Month, newDate.Day, firstDate.Hour, firstDate.Minute, firstDate.Second, firstDate.Millisecond);
Try this:
DateTime s = ...;
s = new DateTime(year, month, day) + s.TimeOfDay;
That preserves the time in the original DateTime.
Try this:
DateTime now = DateTime.Now;
DateTime dateOnly = now.Date;
TimeSpan time = now.TimeOfDay;
dateOnly = DateTime.Parse("5/15/15"); // or whatever date you choose
DateTime newDateTime = dateOnly + time;

Get range of days in a week given a certain day

Suppose my input is March 31, 2015.
How would I be able to get the days of the week that March 31, 2015 is in?
In this case, it should output:
March 29, 2015-April 4, 2015
I found something similar here but it's not quite what I'm looking for as that one takes in the week number while my input is a date itself.
DateTime date = new DateTime(2015, 3, 31);
DateTime weekFirstDay = date.AddDays(DayOfWeek.Sunday - date.DayOfWeek);
DateTime weekLastDay = weekFirstDay.AddDays(6);
Here is a way to get each value separately from a given DateTime
Week start:
public static DateTime GetWeekStartDate(DateTime value)
{
return value.AddDays(-(int)value.DayOfWeek).Date;
}
Week end:
public static DateTime GetWeekEndDate(DateTime value)
{
return value.AddDays(6 - (int)value.DayOfWeek).Date;
}
DayOfWeek firstDayOfWeek = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
DateTime startDate = DateTime.Now;
while (firstDayOfWeek != startDate.DayOfWeek)
{
startDate = startDate.AddDays(-1);
}
DateTime firstDay = startDate.Date;
DateTime lastDay = startDate.AddDays(6);

How to subtract one DateTime from Another and return a double of hours passed

So I have two DateTimes:
date1 = 1/1/2000 12:00:00 AM
date2 = 1/1/2000 12:30:00 AM
How can I subtract date2 from date1 and return a double of .5?
You can subtract one DateTime from another using the - operator (or use the Subtract method) to get a TimeSpan, then use TimeSpan.TotalHours:
DateTime start = new DateTime(2000, 1, 1, 0, 0, 0);
DateTime end = new DateTime(2000, 1, 1, 0, 30, 0);
TimeSpan difference = end - start;
Console.WriteLine(difference.TotalHours); // 0.5
Note that you do not want TimeSpan.Hours, which returns an int in the range -23 to 23 (inclusive); it's the "whole" number of hours.
To get the double you have to use TimeSpann.TotalHours, as Suggested by Jon Skeet:
TimeSpan timeSpann = date2 - date1;
Double difference = timeSpann.TotalHours;
TimeSpann.TotalHours

Date calculations in C#

When given a start date a need to do various calculations on it to produce 3 other dates.
Basically I need to work out what date the user has been billed up to for different frequencies based on the current date.
Bi-Annually (billed twice a year),
Quarterly (billed 4 times a year),
and Two Monthly (billed ever other month).
Take the date 26/04/2008
- BiAnnually: This date would have been last billed on 26/10/2010 and should give the date 26/04/2011.
- Quarterly: This date would have been last billed on 26/01/2011 and should give the date 26/04/2011.
- Two Month: This date would have been last billed on 26/12/2010 and should give the date 26/02/2011.
Assistance is much appreciated.
I think that you can just do like this:
public void FindNextDate(DateTime startDate, int interval);
DateTime today = DateTime.Today;
do {
startDate = startDate.AddMonths(interval);
} while (startDate <= today);
return startDate;
}
Usage:
DateTime startDate = new DateTime(2008, m4, 26);
DateTime bi = FindNextDate(startDate, 6);
DateTime quarterly = FindNextDate(startDate, 3);
DateTime two = FindNextDate(startDate, 2);
I think all you want is something like
DateTime x = YourDateBasis;
y = x.AddMonths(6);
y = x.AddMonths(3);
y = x.AddMonths(2);
Then to edit from comment,
Date Math per the period cycle of the person's account, you would simply need the start and end date and keep adding respective months until you've created all expected months. Almost like that of a loan payment that's due every month for 3 years
DateTime CurrentDate = DateTime.Now;
while( CurrentDate < YourFinalDateInFuture )
{
CurrentDate = CurrentDate.AddMonths( CycleFrequency );
Add Record into your table as needed
Perform other calcs as needed
}
enum BillPeriod
{
TwoMonth = 2,
Quarterly = 3,
SemiAnnually = 6,
BiAnnually = 24
}
public Pair<Datetime, Datetime> BillDates(Datetime currentBillDate, BillPeriod period)
{
Datetime LastBill = currentBillDate.AddMonths(-1 * (int)period);
Datetime NextBill = currentBillDate.AddMonths((int)period);
return new Pair<Datetime,Datetime>(LastBill, NextBill);
}
This is a terrible solution, but it works. Remember, red-light, green-light, refactor. Here, we're at green-light:
namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
Console.WriteLine(GetLastBilled(new DateTime(2008, 4, 26), 6));
Console.WriteLine(GetNextBilled(new DateTime(2008, 4, 26), 6));
Console.WriteLine(GetLastBilled(new DateTime(2008, 4, 26), 4));
Console.WriteLine(GetNextBilled(new DateTime(2008, 4, 26), 4));
Console.WriteLine(GetLastBilled(new DateTime(2008, 4, 26), 2));
Console.WriteLine(GetNextBilled(new DateTime(2008, 4, 26), 2));
Console.WriteLine("Complete...");
Console.ReadKey(true);
}
static DateTime GetLastBilled(DateTime initialDate, int billingInterval) {
// strip time and handle staggered month-end and 2/29
var result = initialDate.Date.AddYears(DateTime.Now.Year - initialDate.Year);
while (result > DateTime.Now.Date) {
result = result.AddMonths(billingInterval * -1);
}
return result;
}
static DateTime GetNextBilled(DateTime initialDate, int billingInterval) {
// strip time and handle staggered month-end and 2/29
var result = initialDate.Date.AddYears(DateTime.Now.Year - initialDate.Year);
while (result > DateTime.Now.Date) {
result = result.AddMonths(billingInterval * -1);
}
result = result.AddMonths(billingInterval);
return result;
}
}
}
This is really tricky. For example, you need to take into account that the date you billed could have been 2/29 on a leap year, and not all months have the same number of days. That's why I did the initialDate.Date.AddYears(DateTime.Now.Year - initialDate.Year); call.

Categories

Resources