I have a date value varFinishDate that I pull form an SQL database and I want to get the 30th of the month after varFinishDate. Except if it’s going to be in February when I want it to be the 28th. What is the best way to do this in C#?
To put it in context, we have programs running and the reports are due at the end of the month after they finish (on the 30th even if there are 31 days). So if it finished any time in April the report is due on the 30th of May and so on, except where they finish in January then the reports are due on the 28th of February.
How about this?
var nextMonth = varFinishDate.AddMonths(1);
var targetDate = new DateTime(
nextMonth.Year,
nextMonth.Month,
nextMonth.Month == 2 ? 28 : 30);
Use DaysInMonth();
So you would have something like
var nextMonth = varFinishDate.AddMonths(1);
if(nextMonth.DaysInMonth() < 30)
nextMonth = new DateTime(nextMonth.Year, nextMonth.Month, 28);
else
nextMonth = new DateTime(nextMonth.Year, nextMonth.Month, 30);
int day = 30;
if (finishedDate.Month == 1)
day = 28;
DateTime nextMonth = finishedDate.AddMonths(1);
DateTime reportDate = new DateTime(nextMonth.Year, nextMonth.Month, day);
This should allow for leap years to also use day 29:
var dueDate = varFinishDate.AddMonths(1);
if ( DateTime.DaysInMonth(dueDate.Year, dueDate.Month) < 30 ) {
dueDate.AddDays(DateTime.DaysInMonth(dueDate.Year, dueDate.Month) - dueDate.Day);
} else {
dueDate = new DateTime(dueDate.Year,dueDate.Month,30);
}
Related
How do I get built-up start hours and end hours that if a user just wants to have done several tasks eg every Monday from 08 to 11 the next x number of weeks.
So how can I just do it in a smart way.
I have MoreAdd which tells how many weeks ahead it should make that way.
When I just create a single task. Then it looks like this.
var sTimer = model.StartTime;
var eTimer = model.EndTime;
SignUpInfo addSignUpInfo = new SignUpInfo
{
CompanyId = companyId,
Title = model.Title,
Info = model.Info,
StartTime = sTimer,
EndTimer = eTimer,
Closed = false,
Pay = PayValue,
TaskDone = false,
CreateTime = DateTime.Now,
CategoriId = model.SelectedKategori
};
_db.SignUpInfo.Add(addSignUpInfo);
_db.SaveChanges();
But how will I only do that if I write 5 then make it one from the next Monday and 5 times forward.
I guess you are struggling with determining the start- and end DateTimes for the next 5 weeks from the next Monday. You could use this method:
static IEnumerable<(DateTime start, DateTime end)> GetTimes(DateTime startTime, DateTime endTime, DayOfWeek startDay, int countWeeks)
{
if(endTime < startTime) throw new ArgumentException("TODO");
TimeSpan diff = endTime - startTime;
int daysUntilWeekDay = ((int) startDay - (int) startTime.DayOfWeek + 7) % 7;
DateTime beginningDate = startTime.AddDays(daysUntilWeekDay);
for (int i = 0; i <= countWeeks; i++)
{
DateTime date = beginningDate.AddDays(7 * i);
yield return (start: date, end:date.Add(diff));
}
}
Example:
DateTime dt = new DateTime(2019, 01, 20, 8, 0, 0); //yesterday, sunday, 8 o clock in the morning
foreach(var x in GetTimes(dt, dt.AddHours(3), DayOfWeek.Monday, 5))
Console.WriteLine("Start:{0} End:{1}", x.start, x.end);
With this method it's easy to build a loop that uses your existing code to save the tasks.
I have a Google API that takes date and time and sets up a event in customers calendar and the problem is I am using date time to add hours to the event when I boot time for 12pm noon For whatever reason, it will be listed in my Google Calendar for the day after at 12am.
Here is the code that sets up the date and the time:
// dd is a drop down for hours 1 to 12 Central Time Zone
int iHour = Convert.ToInt32(dd.SelectedItem.Text);
// and this is the minutes values of 30 or 45
int iMinute = Convert.ToInt32(ddMinute.SelectedItem.Text);
var date = "Nov 19, 2017";
DateTime dt = new DateTime();
dt = Convert.ToDateTime(date);
// If its PM set 12 hours more to it because its a 24 hours clock
if (ddAptAmPm.SelectedValue == "PM")
iHour += 12;
dt = dt.AddHours(iHour);
dt = dt.AddMinutes(iMinute);
var startDate = dt;
var endDate = dt;
string sNotes = "TestingA PI";
string sTitle = "Testas" + " with: " + "ASP.NEt" + " " + "Last Name here";
int length = Convert.ToInt32("30");
endDate = endDate.AddMinutes(length);
var google = new GoogleCalendar();
int value = google.CreateCalendarEvent("email", startDate, endDate, sNotes, sTitle);
Can any one see where did I do this wrong
if (ddAptAmPm.SelectedValue == "PM") // If its PM set 12 hours more to it because its a 24 hours clock
iHour += 12;
should be:
if (ddAptAmPm.SelectedValue == "PM" && iHour < 12) // If its 1-11 PM set 12 hours more to it because its a 24 hours clock
iHour += 12;
else if (ddAptAmPm.SelectedValue == "AM" && iHour == 12)
iHour = 0;
Since 12 + 12 is 24, and today plus 24 hours is the next day.
Another way to write it:
if (iHour == 12) // 12 is **before** 1
iHour = 0;
if (ddAptAmPm.SelectedValue == "PM") // If its PM set 12 hours more to it because its a 24 hours clock
iHour += 12;
Another way you could do it is to construct a date string in a specific format (including the AM or PM designation), and then use DateTime.ParseExact to create your startDate. This way you don't have to do all the conversion from string to int, then add 12 hours if PM was specified, etc.
For example, this code would replace everything you currently have up to and including the startDate assignment:
// This assumes that ddAptAmPm.SelectedValue will be "AM" or "PM"
var dateString = string.Format("Nov 19, 2017 {0}:{1} {2}", dd.SelectedItem.Text,
ddMinute.SelectedItem.Text, ddAptAmPm.SelectedValue);
// In a format string, tt is a placeholder for AM/PM
var startDate = DateTime.ParseExact(dateString, "MMM dd, yyyy h:m tt",
CultureInfo.InvariantCulture);
You can read more about Date and Time Format Strings here.
Can anyone please help me, how do I calculate fortnightly (14 days) logic using C#?, for a example 14 days start following sequence order on February
Monday start date 8 Feb (next 22 Feb, 7 March, 21 March etc..)
Thursday start date 11 February (next 25 Feb, 10 March, 24 March etc..)
Friday start date 12 February (next 26 Feb, 11 March, 25 March etc..)
My logic is not working for the 14 days day display, because 15 February will come 14 days add, it’ll display “First14days” date 29 February 2016, it is a wrong.
This is C# logic
Day.Days value are Monday, Thursday, Friday etc..
foreach (var Day in day)
{
Example Day.Days = Monday
Int 14days = (((int)Enum.Parse(typeof(DayOfWeek), Day.Days) - (int)today.DayOfWeek + 14) % 7);
DateTime First14days = today.AddDays(14days);
}
My output should be
Simply add TimeSpan.FromDays(14) to any date to get a fortnight further on
DateTime startDate = DateTime.Now;
TimeSpan fortnight = TimeSpan.FromDays(14);
for (int i = 0; i < 6; i++)
{
startDate += fortnight;
Console.WriteLine($"Date for fortnight {i}: {startDate:D}");
}
If I understand correct your question this code will be working for you.
DateTime time = DateTime.Now;
DateTime anotherTime = DateTime.Now;
var allTimes = new HashSet<DateTime>();
for (int i = 0; i < 6; i++)
{
anotherTime = time.AddDays(14);
time = anotherTime;
Console.WriteLine(anotherTime.ToLongDateString());
allTimes.Add(time);
}
// or with your example is possible to like this code.
foreach (var Day in day)
{
anotherTime = Day.AddDays(14);
time = anotherTime;
Console.WriteLine(anotherTime.ToLongDateString());
allTimes.Add(time);
}
First create two DataTime objects. then foreach few times, and in for loop statement set anotherTime = time.AddDays(14) after that set time = anotherTime.
//Output:
//Saturday, February 27, 2016
//Saturday, March 12, 2016
//Saturday, March 26, 2016
//Saturday, April 09, 2016
//Saturday, April 23, 2016
//Saturday, May 07, 2016
EDIT:
I create and HashSet where you can save all you DateTime who you make it.
So here's you all-in-one solution:
// determine the date of next given weekday
DateTime date = GetNextWeekday(DateTime.Today, DayOfWeek.Tuesday);
// create a list and add the start date (if you want)
List<DateTime> fortnights = new List<DateTime>() { date };
// add as many "fortnights" as you like (e.g. 5)
for (int i = 0; i < 5; i++)
{
date = date.Add(TimeSpan.FromDays(14));
fortnights.Add(date);
}
// use your list (here: just for printing the list in a console app)
foreach (DateTime d in fortnights)
{
Console.WriteLine(d.ToLongDateString());
}
Method to get the next weekday, from:
https://stackoverflow.com/a/6346190/2019384
public static DateTime GetNextWeekday(DateTime start, DayOfWeek day)
{
// The (... + 7) % 7 ensures we end up with a value in the range [0, 6]
int daysToAdd = ((int) day - (int) start.DayOfWeek + 7) % 7;
return start.AddDays(daysToAdd);
}
I need to find the week numbers of a given date rage in C#.
Ex: date between 01/01/2014 and 14/01/2014
Week numbers are 1st,2nd and 3rd weeks, likewise.
Thanks.
Not the smartest way, but works!
var d1 = new DateTime(2014, 1, 1);
var d2 = new DateTime(2014, 1, 14);
var currentCulture = CultureInfo.CurrentCulture;
var weeks = new List<int>();
for (var dt = d1; dt < d2; dt =dt.AddDays(1))
{
var weekNo = currentCulture.Calendar.GetWeekOfYear(
dt,
currentCulture.DateTimeFormat.CalendarWeekRule,
currentCulture.DateTimeFormat.FirstDayOfWeek);
if(!weeks.Contains(weekNo))
weeks.Add(weekNo);
}
This should work:
public List<int> Weeks(DateTime start, DateTime end)
{
List<int> weeks=new List<int>();
var Week=(int)Math.Floor((double)start.DayOfYear/7.0); //starting week number
for (DateTime t = start; t < end; t = t.AddDays(7))
{
weeks.Add(Week);
Week++;
}
return weeks;
}
All this does is get the week of the start date, then loops through one week at a time until you get to the end date, incrementing the week and adding it to the list of weeks.
OK, let's start with a simple, unoptimized example. We'll simply examine every date between those dates and check what week of the year it is.
We can do that with a simple loop:
var end = new DateTime(2014, 1, 14);
for (var date = new DateTime(2014, 1, 1); date <= end; date = date.AddDays(1))
{
}
This will simply loop over every day between two dates. Now we need to examine those days to determine their day of week. To do this you need to consider a few things: What is the first day of a week? Sunday? Monday? Are we assuming gregorian calendar?
For our example, let's assume the first day of the week is a Sunday and we are indeed using the Gregorian calendar. Then we will check each date, and keep a list of unique weeks of the year using a HashSet:
var weekNumber = new HashSet<int>();
var end = new DateTime(2014, 1, 14);
var calendar = new GregorianCalendar();
for (var date = new DateTime(2014, 1, 1); date <= end; date = date.AddDays(1))
{
weekNumber.Add(calendar.GetWeekOfYear(date, CalendarWeekRule.FirstDay, DayOfWeek.Sunday));
}
The weekNumber Hashset now contains the weeks of the year.
Is this optimized? No. It checks far more dates than it needs to, but the implementation is simple and fast enough. Optimizing can be done as a separate task.
Easy. Here's the code that determines the week of the year for a single date. This should get you going:
int WeekOfYear(DateTime date, DayOfWeek dayOfWeekStart) {
//Find the first day of the year that's the start of week day. If it's not 1/1,
//then we have a first partial week.
bool firstPartialWeek = false;
DateTime firstFullWeekStart = new DateTime(date.Year, 1, 1);
while(firstFullWeekStart.DayOfWeekDay != dayOfWeekStart) {
firstFullWeekStart = firstOfWeek.AddDays(1);
firstPartialWeek = true;
}
//Return the week by integer dividing the date difference by seven,
//and adding in the potential first partial week
return (firstPartialWeek ? 1 : 0) + ((date - firstFullWeekStart).TotalDays / 7);
}
I need to know Jerusalem Current time.
That code taking server time but I need Jerusalem time:
DateTime currentTime = DateTime.Now;
dayName = currentTime.DayOfWeek;
Edit:
with help of Vinoth answer(I took only the AddHours(2) part) it should be like that (not works):
DateTime currentTime = DateTime.Now;
currentTime=currentTime.AddHours(2);//Jerusalem Time
dayName = currentTime.DayOfWeek;
Edit2:my improvement (ToUniversalTime())
DateTime currentTime = DateTime.Now;
currentTime=currentTime.ToUniversalTime().AddHours(2);//Jerusalem Time
dayName = currentTime.DayOfWeek;
This will help you. I have used this is one of my app. Jus pasting the code
public static DateTime GetIsraelTime(DateTime d) {
d = d.AddHours(2); // Israel is at GMT+2
// April 2nd, 2:00 AM
DateTime DSTStart = new DateTime(d.Year, 4, 2, 2, 0 ,0);
while (DSTStart.DayOfWeek != DayOfWeek.Friday)
DSTStart = DSTStart.AddDays(-1);
CultureInfo jewishCulture = CultureInfo.CreateSpecificCulture("he-IL");
System.Globalization.HebrewCalendar cal =
new System.Globalization.HebrewCalendar();
jewishCulture.DateTimeFormat.Calendar = cal;
// Yom HaKipurim, at the start of the next Jewish year, 2:00 AM
DateTime DSTFinish =
new DateTime(cal.GetYear(DSTStart)+1, 1, 10, 2, 0 ,0, cal);
while (DSTFinish.DayOfWeek != DayOfWeek.Sunday)
DSTFinish= DSTFinish.AddDays(-1);
if (d>DSTStart && d<DSTFinish)
d = d.AddHours(1);
return (d);
}
var israelTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.Now, "Israel Standard Time")
Complete time zones ids list can be found here.