Days between two dates in asp.net - c#

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>

Related

Return month names from current month

I need help in C# getting month names from current month, meaning user inputs a month(name) and will return the list of months from the starting month until the current month.
Example; user inputs "August" and current month is "December" so it should return "August, September, October, November, December".
I've done a few steps but still can't get to it.
1st try:
string pattern = ("MMMM/yyyy");
Console.WriteLine("Enter Month: MMMM/yyyy");
DateTime inpMonth = DateTime.ParseExact(Console.ReadLine(),pattern,System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);
string last = inpMonth.ToString("MMMM/yyyy");
DateTime date = DateTime.Now;
string curr = date.ToString("MMMM/yyyy");
2nd Try(new step):
//First Date
DateTime 1Date = new DateTime(2020, 12, 01);
//Second Date
DateTime 2Date =new DateTime(2019, 01, 01);
int month1 = (2Date.Month - 1Date.Month);
int month2 = (2Date.Year - 1Date.Year) * 12;
int months = month1 + month2;
string mon = months.DateTime.ToString("MMMM"); //trying to convert the month number to month name
Both try seems to not get any close result..
The following code will output to the result you requested:
var start = "August";
var today = DateTime.Today;
var date = new DateTime(today.Year, DateTime.ParseExact(start, "MMMM", CultureInfo.CurrentCulture).Month, 1);
while (date < today)
{
Console.WriteLine($"{date:MMMM}");
date = date.AddMonths(1);
}

Calculating dates expecting double

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;

C# datetime scope

Assuming I can not change service that returns data, I am left with
var date = "20140231";
var scope = DateTime.ParseExact(date, "yyyyMMdd", CultureInfo.CurrentCulture);
Clearly "20140231" is lazy way of saying end of February. What is the cleanest way to get last date of February with input of "20140231"?
There is 1 constraint - this should work with .net 2.0.
string date = "20140231";
DateTime result;
int year = Convert.ToInt32(date.Substring(0, 4));
int month = Convert.ToInt32(date.Substring(4, 2));
int day = Convert.ToInt32(date.Substring(6, 2));
result = new DateTime(year, month, Math.Min(DateTime.DaysInMonth(year, month), day));
February can have only 28 or 29 days depends on current year is a leap year or not.
It can't have 30 or 31 days in any year. That's why you can't parse your 20140231 string successfully.
You can clearly get the last day of February like;
DateTime lastDayOfFebruary = (new DateTime(2014, 2, 1)).AddMonths(1).AddDays(-1);
If your service always get year as a first 4 character, you can use .Substring() to get year and pass DateTime constructor as a year.
var date = "20140231";
string year = date.Substring(0, 4);
DateTime lastDayOfFebruary = (new DateTime(int.Parse(year), 2, 1)).AddMonths(1).AddDays(-1);
You could create a while, cut the date in pieces, and keep subtracting one from the day part until it is a valid date. This should really be fixed on the entry side though.
Try this:
var date = "20140231";
DateTime scope;
bool dateValid = DateTime.TryParseExact(date, "yyyyMMdd", CultureInfo.CurrentCulture, DateTimeStyles.None, out scope);
while (!dateValid)
{
string yearMonth = date.Substring(0, 4);
int day = Convert.ToInt32(date.Substring(6, 2));
if (day > 1)
{
day--;
}
else
{
break;
}
date = yearMonth + day.ToString().PadLeft(2, '0');
dateValid = DateTime.TryParseExact(date, "yyyyMMdd", CultureInfo.CurrentCulture, DateTimeStyles.None, out scope);
}

Getting first and last day of the current month

I have here 2 datepicker for start date and end date.
how can I get the first day and last day of the current month
rdpStartDate.SelectedDate = DateTime.Now;
rdpEndDate.SelectedDate = DateTime.Now;
DateTime now = DateTime.Now;
var startDate = new DateTime(now.Year, now.Month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);
var now = DateTime.Now;
var first = new DateTime(now.Year, now.Month, 1);
var last = first.AddMonths(1).AddDays(-1);
You could also use DateTime.DaysInMonth method:
var last = new DateTime(now.Year, now.Month, DateTime.DaysInMonth(now.Year, now.Month));
var myDate = DateTime.Now;
var startOfMonth = new DateTime(myDate.Year, myDate.Month, 1);
var endOfMonth = startOfMonth.AddMonths(1).AddDays(-1);
That should give you what you need.
Try this code it is already built in c#
int lastDay = DateTime.DaysInMonth (2014, 2);
and the first day is always 1.
Good Luck!
An alternative way is to use DateTime.DaysInMonth to get the number of days in the current month as suggested by #Jade
Since we know the first day of the month will always 1 we can use it as default for the first day with the current Month & year as current.year,current.Month,1.
var now = DateTime.Now; // get the current DateTime
//Get the number of days in the current month
int daysInMonth = DateTime.DaysInMonth (now.Year, now.Month);
//First day of the month is always 1
var firstDay = new DateTime(now.Year,now.Month,1);
//Last day will be similar to the number of days calculated above
var lastDay = new DateTime(now.Year,now.Month,daysInMonth);
//So
rdpStartDate.SelectedDate = firstDay;
rdpEndDate.SelectedDate = lastDay;
string firstdayofyear = new DateTime(DateTime.Now.Year, 1, 1).ToString("MM-dd-yyyy");
string lastdayofyear = new DateTime(DateTime.Now.Year, 12, 31).ToString("MM-dd-yyyy");
string firstdayofmonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString("MM-dd-yyyy");
string lastdayofmonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddDays(-1).ToString("MM-dd-yyyy");

C# subtract time (hours minutes)

Hello Everyone I have some interesting situation.
I want to count how many hours (in minutes) is from 20:00 to 01:00 AM, but i Don't know how, because what i have done is:
pabaigosLaikoLaukelis = 01:00;
pradziosLaikoLaukelis = 20:00;
TimeSpan dt = Convert.ToDateTime(pabaigosLaikoLaukelis)- Convert.ToDateTime(pradziosLaikoLaukelis);
int minutes = (int)dt.TotalMinutes;
And i get result -> -1140 minutes, but I need that answer to be just 5 hours from 20:00 to 01:00.
I know that it is quite easy, but i have no idea how to do it.
you could do something like this
//Datetime(Year,month,day,hour,min,sec)
DateTime date1 = new DateTime(2012, 1, 1, 20, 0, 0);
DateTime date2 = new DateTime(2012, 1, 2, 1, 0, 0);
string minutes = (date2.Subtract(date1).TotalMinutes).ToString();
Tested and works 300 minutes (5 hours)
Use full date time strings that contain day part, to show that 01:00 AM is one day later than 20:00 - like following:
int minutes = Convert.ToDateTime("01/02/2012 01:00").Substract(Convert.ToDateTime("01/01/2012 20:00")).TotalMinutes;
You need to specify the Day, you are subracting (Today 1:00 AM) - (Today 8:00 PM)
I think you need to subract (Tommorrow 1:00 AM) - (Today 8:00 PM)
Be careful with adding one day to the endTime, because then the difference between 20:00 and 22:00 will be 26 hours instead of 2!
Just check whether the difference is positive (same day) or negative (next day)
string pabaigosLaikoLaukelis = "01:00";
string pradziosLaikoLaukelis = "20:00";
// This should be 5 hours
TimeSpan dt = Convert.ToDateTime(pabaigosLaikoLaukelis) - Convert.ToDateTime(pradziosLaikoLaukelis);
int hours = (int)dt.TotalHours;
hours = hours < 0 ? 24 + hours : hours;
// This should be 19 hours
dt = Convert.ToDateTime(pradziosLaikoLaukelis) - Convert.ToDateTime(pabaigosLaikoLaukelis);
hours = (int)dt.TotalHours;
hours = hours < 0 ? 24 + hours : hours;
A bit of preparation of the two string variables is required before attempting data calculations
string pabaigosLaikoLaukelis = "01:00";
string pradziosLaikoLaukelis = "20:00";
pabaigosLaikoLaukelis = DateTime.Today.ToString("dd/MM/yyyy") + " " + pabaigosLaikoLaukelis;
pradziosLaikoLaukelis = DateTime.Today.AddDays(-1).ToString("dd/MM/yyyy") + " " + pradziosLaikoLaukelis;
TimeSpan dt = Convert.ToDateTime(pabaigosLaikoLaukelis) - Convert.ToDateTime(pradziosLaikoLaukelis);
Console.WriteLine("{0:D2}:{1:D2}", dt.Hours, dt.Minutes);
You need to add a day to the first TimeSpan and use TotalHours.
var pabaigosLaikoLaukelis = "01:00";
var pradziosLaikoLaukelis = "20:00";
var oneDayTimeSpan = new TimeSpan(1, 0, 0, 0);
TimeSpan dt = TimeSpan.Parse(pabaigosLaikoLaukelis).Add(oneDayTimeSpan) - TimeSpan.Parse(pradziosLaikoLaukelis);
int minutes = (int)dt.TotalHours; // 5 hours
Using associative operations:
var pabaigosLaikoLaukelis = "21:00";
var pradziosLaikoLaukelis = "20:00";
var leftHours = (int)TimeSpan.Parse(pabaigosLaikoLaukelis).TotalHours;
var rightHours = (int)TimeSpan.Parse(pradziosLaikoLaukelis).TotalHours;
// Now we do a Modulus operation which will assure
// 23 > hours > 0
// Make sure to check that leftHours != 0 or rightHours != 0
int hours = (Math.Abs(leftHours * rightHours) + leftHours) % rightHours; //Modulus
var hoursTimeSpan = TimeSpan.FromHours(hours);
How about this:
pabaigosLaikoLaukelis = 01:00;
pradziosLaikoLaukelis = 20:00;
TimeSpan startTime = Convert.ToDateTime(pradziosLaikoLaukelis).TimeOfDay;
TimeSpan endTime = Convert.ToDateTime(pabaigosLaikoLaukelis).TimeOfDay;
TimeSpan diff = endTime > startTime ? endTime - startTime : endTime - startTime + TimeSpan.FromDays(1);
int minutes = (int)diff.TotalMinutes;

Categories

Resources