how can I calculate if a date (in DateTime format) is 6 month later or not from my BirthDate (in DateTime format)?
Use DateTime AddMonth method
https://msdn.microsoft.com/ru-ru/library/system.datetime.addmonths(v=vs.110).aspx
var dat = new DateTime(2015, 12, 31);
var dat2 = new DateTime(2015, 12, 31);
if (dat.AddMonths(6) < dat2) { ... }
You should use DateTime.AddMonths :
DateTime dt;
DateTime birthDate;
if (dt <= birthDate.AddMonths(6))
{
}
enter your birth date, calculate your next birthday and compare the dates,
var born = new DateTime(1900, 02, 01);
var checkdate = DateTime.Now;
var nextBirthday = new DateTime(DateTime.Now.Year, born.Month, born.Day);
if (nextBirthday < DateTime.Now)
{
nextBirthday = new DateTime(DateTime.Now.Year + 1, born.Month, born.Day);
}
if (checkdate.AddMonths(6) < nextBirthday)
{
Console.WriteLine("date is 6 months later then birthday");
}
else
{
Console.WriteLine("wait for it");
}
DateTime birthDate=new DateTime(year,month,day);
DateTime dateToCompare = new DateTime(year, month, day);
if(dateToCompare >= birthdate.AddMonths(6))
{
//DoSomething
}
You could calculte the difference between dates using Subtract method and calculate how many months you have between these dates, for sample:
DateTime birthDay = /* some date */;
DateTime someDate = /* some date */;
var months = someDate.Subtract(birthDay).Days / (365.25 / 12);
This answer provides a good helper for Dates:
https://stackoverflow.com/a/33287670/316799
Related
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);
}
I have two datetimepickers. So I want to get the days of the week between the selected values.
Example: date1 = 14/1/2015 and date2 = 17/1/2015
So the result should be: days = Wed. Thu. Fri. Sat.
You want to get the DayOfWeeks of all DateTimes between two dates?
int daysDiff = (date2 - date1).Days;
List<DayOfWeek> days = Enumerable.Range(0, daysDiff + 1) // +1 because you want to include start and end date
.Select(d => date1.AddDays(d).DayOfWeek)
.ToList();
You need to add using System.Linq;
You can easily iterate your DateTime values like;
var dt1 = new DateTime(2015, 1, 14);
var dt2 = new DateTime(2015, 1, 17);
while (dt2 >= dt1)
{
Console.WriteLine(dt1.DayOfWeek);
dt1 = dt1.AddDays(1);
}
Result will be;
Wednesday
Thursday
Friday
Saturday
If you wanna their abbreviated day names as Wed, Thu, Fri, Sat, you can use "ddd" custom format specifier with a english-based culture (like InvariantCulture) like;
var dt1 = new DateTime(2015, 1, 14);
var dt2 = new DateTime(2015, 1, 17);
while (dt2 >= dt1)
{
Console.WriteLine(dt1.ToString("ddd", CultureInfo.InvariantCulture));
dt1 = dt1.AddDays(1);
}
Another alternative, which includes non-usual use of a for-loop and the yield return statement:
void Main()
{
var daysOfWeek = DaysBetween(
new DateTime(2015, 1, 14),
new DateTime(2015, 1, 17));
Console.WriteLine(
String.Join(", ", daysOfWeek.Select(d => d.ToString().Substring(0, 3))));
// prints: Wed, Thu, Fri, Sat
}
IEnumerable<DayOfWeek> DaysBetween(DateTime start, DateTime end)
{
for (var dateTime = start; dateTime <= end; dateTime = dateTime.AddDays(1))
{
yield return dateTime.DayOfWeek;
}
}
having a DateTime variable, for example:
DateTime testDate = new DateTime(2011,12,15,00,00,00);
how can I implement a foreach loop for every hour of this day?
Something like:
foreach (int myHour in testDate.Date)
{
}
but in this way does not compile.
It is not a good idea to loop 24, because this will not work on days with 25 or 23 hours (time change, daylight saving...).
Use the AddHour function and a target date.
DateTime testDate = new DateTime(2011, 12, 15, 00, 00, 00, DateTimeKind.Local);
DateTime endDate = testDate.AddDays(1);
while (testDate.Date != endDate.Date)
{
Console.WriteLine(testDate.ToString());
testDate = testDate.AddHours(1);
}
More Information
MSDN - DateTimeKind Enumeration
Use for instead:
DateTime date = new DateTime(2011,12,15);
for(int i = 0; i < 24; i++)
{
DateTime time = date.AddHours(i);
...
}
If you really want to use foreach, you could create an extension method like this:
static class DateTimeExtensions
{
public static IEnumerable<DateTime> GetHours(this DateTime date)
{
date = date.Date; // truncate hours
for(int i = 0; i < 24; i++)
{
yield return date.AddHours(i);
}
}
}
...
DateTime date = new DateTime(2011,12,15);
foreach (DateTime time in date.GetHours())
{
...
}
For those who don't like plain old for loops :) :
DateTime testDate = new DateTime(2011,12,15,00,00,00);
foreach (int hour in Enumerable.Range(0,24)) {
DateTime dateWithHour = testDate.AddHours(hour);
}
foreach loop works in list but here testDate.Date never gives you hour. so in substitution of it use for loop or do while or while loop.
The code below allows you to cycle through the hours of the day but also starting from a specific hour. It could be simpler if you do not need to support starting from an hour offset.
DateTime testDate = new DateTime(2011,12,15,13,00,00);
var hoursLeft = 24 - testDate.Hour;
for (var hour = 1; hour < hoursLeft; hour++)
{
var nextDate = testDate.AddHours(hour);
Console.WriteLine(nextDate);
}
To get the hours in DLS time use this:
DateTime testDate = new DateTime(2017, 03, 26, 00, 00, 00, DateTimeKind.Local);
DateTime endDate = testDate.AddDays(1);
//these dates also contain time!
var start = TimeZone.CurrentTimeZone.GetDaylightChanges(testDate.Year).Start;
var end = TimeZone.CurrentTimeZone.GetDaylightChanges(testDate.Year).End;
var hoursInDay = new List<DateTime>();
while (testDate.Date != endDate.Date)
{
if (start == testDate)
{
//this day have 23 hours, and should skip this hour.
testDate = testDate.AddHours(1);
continue;
}
hoursInDay.Add(testDate);
if (end == testDate)
{
hoursInDay.Add(testDate); //this day has 25 hours. add this extra hour
}
testDate = testDate.AddHours(1);
}
I'm in Denmark, so when I run this it has only 23 hours.
Iterate over all 24 hours of the day:
DateTime testDate = new DateTime(2011, 12, 15);
for (int i = 0; i < 24; i++)
{
DateTime hour = testDate.Date.AddHours(i);
// Your code here
}
DateTime today = DateTime.Today;
DateTime tomorrow = today.AddDays(1);
for ( var i = today; i <= tomorrow; i = i.AddHours(1))
{
// your code
}
simply do this
DateTime testDate = new DateTime(2011, 12, 15, 10, 00, 00);
for (int i = testDate.Hour; i < 24; i++)
{
//do what ever
}
I have two date time ranges 8/27/2011 and 8/31/2011 how i can make get all days ? like that : 8/28/2011, 8/29/2011 and 8/30/2011
thanks
Here is a code snippet to get all days between a start and end date inclusive:
DateTime today = new DateTime(2011, 8, 29);
DateTime nextWeek = new DateTime(2011, 9, 4);
TimeSpan difference = nextWeek - today;
List<DateTime> days = new List<DateTime>();
for (int i = 0; i <= difference.Days; i++)
{
days.Add(today.AddDays(i));
}
foreach (var dateTime in days)
{
Console.WriteLine(dateTime);
}
Console.ReadLine();
Output:
8/29/2011 12:00:00 AM
8/30/2011 12:00:00 AM
8/31/2011 12:00:00 AM
9/1/2011 12:00:00 AM
9/2/2011 12:00:00 AM
9/3/2011 12:00:00 AM
9/4/2011 12:00:00 AM
To piggy back off of davecoulter, if you need to do this all over your application for your DateTime objects, you might want to define an extenion method for your DateTime object.
void Main()
{
DateTime today = new DateTime(2011, 8, 29);
DateTime nextWeek = new DateTime(2011, 9, 4);
foreach (DateTime dateTime in today.ListAllDates(nextWeek))
{
Console.WriteLine(dateTime);
}
Console.ReadLine();
}
public static class DateTimeExtenions
{
public static IEnumerable<DateTime> ListAllDates(this DateTime lhs, DateTime futureDate)
{
List<DateTime> dateRange = new List<DateTime>();
TimeSpan difference = (futureDate - lhs);
for(int i = 0; i <= difference.Days; i++)
{
dateRange.Add(lhs.AddDays(i));
}
return dateRange;
}
}
You can copy this straight into LinqPad and run as program to test it out.
using System;
using System.Linq;
var startDate = new DateTime(2011, 9, 1);
var days = Enumerable.Range(0, 10).Select(n => startDate.AddDays(n));
Create a new date from both datetimes datetime to make sure that it they are at the start of the day. Then run a for loop that works from starttime.Ticks to endtime.Ticks and increments by TimeSpan.TicksPerDay and create a new DateTime that you add to a list for every value. The example below will not include the end date but you can easily fix that.
var start= new DateTime(2009,01,01).Ticks;
var end= new DateTime(2009,01,10).Ticks;
List<DateTime> dates = new List<DateTime>();
for (var i = start; i < end; i+=TimeSpan.TicksPerDay) {
dates.Add(new DateTime(i));
}
Or you could loop through between them and call the AddDays method.
I have a financial year's month end value 2.
How would i calculate the financial year DateTime startDate and DateTime endDate from that value?
You can do:
DateTime startDate = new DateTime(DateTime.Today.Year, 2, 1); // 1st Feb this year
DateTime endDate = new DateTime(DateTime.Today.Year+1, 2, 1).AddDays(-1); // Last day in January next year
Does that solve your problem?
I assume you mean Feb by 2.
This code should do this:
DateTime start = new DateTime(2010,2,1);
DateTime end = start.AddMonths(12).AddDays(-1);
Console.WriteLine(start);
Console.WriteLine(end);
Output:
01-Feb-10 12:00:00 AM
31-Jan-11 12:00:00 AM
Here is my version for calculating the Fiscal Year Start Date. It checks the StartMonth against the current month, and will adjust the year.
private DateTime? FiscalYearStartDate() {
int fyStartMonth = 2;
var dte = new DateTime(DateTime.Today.Year, fyStartMonth, 1); // 1st April this year
if (DateTime.Today.Month >= fyStartMonth) {
//Do nothing, since this is the correct calendar year for this Fiscal Year
} else {
//The FY start last calendar year, so subtract a year
dte = dte.AddYears(-1);
}
return dte;
}
You can easily calculate the End Date like others have done, by adding +1 Year, and then subtracting 1 Day (thanks to Johannes Rudolph).
DateTime endDate = new DateTime(DateTime.Today.Year+1, 2, 1).AddDays(-1);
If your current date is 14/01/2021
Then the Indian financial Year is 01/04/2020 to 31/03/2021
Use the following code for perfect output.
DateTime CurrentDate = DateTime.Now;
int CurrentMonth = CurrentDate.Month;
if (CurrentMonth >= 4)//4 is the first month of the financial year.
{
txtFromDate.Text = new DateTime(CurrentDate.Year, 4, 1).ToString(CS.ddMMyyyy);
txtToDate.Text = new DateTime(CurrentDate.Year + 1, 4, 1).AddDays(-1).ToString(CS.ddMMyyyy);
}
else
{
txtFromDate.Text = new DateTime(CurrentDate.Year - 1, 4, 1).ToString(CS.ddMMyyyy);
txtToDate.Text = new DateTime(CurrentDate.Year, 4, 1).AddDays(-1).ToString(CS.ddMMyyyy);
}
public static (DateTime, DateTime) GetCurrentFinacialYearDateRange()
{
if(DateTime.Now.Month >= 7)
{
DateTime startDate = new DateTime(DateTime.Today.Year, 7, 1); // 1st July this year
DateTime endDate = new DateTime(DateTime.Today.Year + 1, 7, 1).AddDays(-1); // Last day in June next year
return (startDate, endDate);
}
else
{
DateTime startDate = new DateTime(DateTime.Today.Year-1, 7, 1); // 1st July this year
DateTime endDate = new DateTime(DateTime.Today.Year, 7, 1).AddDays(-1); // Last day in June next year
return (startDate, endDate);
}
}