I am programming a C# Windows application for a clinic and i stored days of works for every doctor for example
Dr.John works every Monday and Tuesday how i can enable dates in DateTimePicker for dates that only match the specific days and disable other days .
I don't know what are the methods and functions can help in that
Instead of the DateTimePicker you can
create a form on the fly
add a MonthCalendar to it
add either valid or invalid dates to the BoldDates collection
code the DateChanged event
test to see if a valid date was selected
add it to the list of dates picked
Details depend on what you want: A single date or a range, etc.
Make sure to trim the time portion, mabe like this for adding dates:
List<DateTime> bold = new List<DateTime>();
for (int i = 0; i < 3; i++)
bold.Add(DateTime.Now.AddDays(i*3).Date);
monthCalendar1.BoldedDates = bold.ToArray();
To select only valid dates maybe code like this:
List<DateTime> selected = new List<DateTime>();
private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
for (DateTime dt = monthCalendar1.SelectionStart.Date;
dt.Date <= monthCalendar1.SelectionEnd.Date;
dt = dt.AddDays(1))
{
if (!monthCalendar1.BoldedDates.Contains(dt)
&& !selected.Contains(dt)) selected.Add(dt.Date);
}
}
Unfortunately the options to set any stylings are limited to bolding dates. No colors or other visual clues seem to be possible.
So for anything really nice you will have to build a date picker yourself..
Related
I am using two datetimepickers in my form. I want to grey out future dates and dates previous to (sysdate -60) in both the datetimepickers .
I have set min and max for both ddatetimepickers when the form loads. This only shows me dates in the set min & max range.
private void form_main_Load(object sender, EventArgs e)
{
dateTimePicker1.MaxDate = DateTime.Today;
dateTimePicker2.MaxDate = DateTime.Today;
dateTimePicker1.MinDate = DateTime.Today.AddDays(-60);
dateTimePicker2.MinDate = DateTime.Today.AddDays(-60);
}
But I want all the dates to be visible but as said above, future and dates previous to (sysdate -60) should be greyed out. Is it possible ?
This is for a program at work. I don't have access to the code right now, but I really want to figure this out, so I wrote a quick program at home that is a mimic of my work project.
I need to know if that date is within 3 working days of a "holiday". If it is, then the selected date must be incremented by one to skip over the holiday. Example:
If there is a holiday on "01/19/2018" and a user selects "01/16/2018", then the program must skip the 19th and then set the closing date as "01/20/2018". Now if I do pure if/then statements, I can get it to work as expected, but the problem then becomes: "what if both 01/19/2018 AND 01/20/2018 are holidays?" This is where I'm stuck.
At work, I'm using a SQL table that already has a column for dates in "MM/dd/yyyy" format (so those dates are my list source that I am checking against.) The user opens a calendar and selects a date. I'm actually parsing an XML file that is created by another method that actually touches the database then using XElement for an iteration that puts all those dates in a string list.)
This is the code in my pseudo work program:
private void button1_Click(object sender, EventArgs e)
{
DateTime dt = DateTime.Now;
txtLog.Text = dt.ToString("MM/dd/yy") + Environment.NewLine;
List<string> allexemptdays = new List<string>();
string[] days = { "11/19/2018", "11/20/2018" };
foreach (string a in days)
{
allexemptdays.Add(a);
}
foreach (string a in allexemptdays)
{
ToLog(a);
}
DateTime eq = DateTime.Parse(txtDate.Text);
string thefrustrationisreal = eq.ToString("MM/dd/yy");
if (Math.Abs(DateTime.Now.Subtract(eq).Days) <= 3)
{
MessageBox.Show("Date exemption found.");
}
}
private void ToLog(string a)
{
txtLog.Text += ("Array value to list: " + a + Environment.NewLine);
}
private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
txtDate.Text = monthCalendar1.SelectionStart.ToString("MM/dd/yy");
}
Obviously I understand "DateTime.Now" doesn't reflect what I require, but I was just playing more with the DateTime class.
So in short: I'm creating an array with the dates (similar to my real program)
Iterating through them, adding them to a list. Now I need to check if the selected date falls within 3 days of the predefined date from a returned value from my sql table.
If a date is found, move the closing date up a day; however, if holidays in a row are found, then skip those two dates altogether. I can do this on a one by one basis (using if/then) but this doesn't work well if two holidays are back to back of each other.
As a side note, I want to be able to tell if the selected date is within 3 days AND moves over to another month, but I think I can handle that with DateTime, checking the days in a month and incrementing when needed (or I'm sure DateTime could do that for me actually.) I'm not too worried about this concern though at this point.
I did accept Mike's answer as it does work as intended, but! I now have a different issue
Now the "days.count()" holds a persistent number after the user selects a date beyond the holidays. Example: Selecting January 21 2017 returns "Janurary 26 2017" as the closing date because it's still counting the 20th and 21st as holidays affected by the range, when it should just set the closing date now at "Janurary 24th 2017"
I've played around with the code provided; I can't find a good way to fix it. I was thinking something along the lines of:
If(selectedDate.AddDays(3) >= holidaydate) then do a check for another day through the datetime list, but I'd still be making that way more complicated than it should be (I think.)
Last entry I'll do to this post (I'm considering this post solved now):
Matt's answer I selected does work to an extent and I appreciate his help. Problem is, the .Count() never resets, so if you go past the holiday(s) dates, it always holds onto the skipped days (so instead of going to 3 days ahead of the selected date, it'll go (3+the total number of days counted))
In the event someone else comes across a situation like this, here's what I ended up doing:
Downloaded the "WorkingDaysManagement" reference, instructions from:
https://github.com/Opturne/WorkingDaysManagement
the code I ultimately used is:
private void button1_Click(object sender, EventArgs e)
{
txtLog.Text = null;
DateTime dt = DateTime.Now;
var sd = (DateTime.Parse(txtDate.Text));
Console.WriteLine(sd.ToShortDateString());
var listHolidays = new List<DateTime>
{
new DateTime(2017, 12, 24),
new DateTime(2017, 12, 25)
};
var listWeekEnd = new List<DayOfWeek>
{
DayOfWeek.Saturday,
DayOfWeek.Sunday
};
var helper = new WorkingDayHelper(listHolidays,listWeekEnd);
foreach(DateTime s in helper.GetSpanDates(sd,3))
{
Console.WriteLine("Current iteration date: "+s.ToShortDateString());
}
var nextworkday = (helper.GetSpanDates(sd, 3).Last().ToString());
txtLog.Text += ("Next working day available: " + nextworkday + Environment.NewLine);
if(helper.IsWorkingDay(sd)==true)
{
txtLog.Text += ("It is a working a day." + Environment.NewLine);
}
else
{
txtLog.Text += ("NOT a working day!" + Environment.NewLine);
}
txtEndDate.Text = nextworkday;
}
The author of the plugin was gracious enough to put his work under the MIT license as well.
Let's say you have parsed all the date strings from the database into a List<DateTime> namely holidays. Then you can do something like
// Parsed holidays in a list, we will use LINQ against it.
var holidays = new List<DateTime> {
new DateTime(2017, 1, 19),
new DateTime(2017, 1, 20),
};
// Selected Date. In your case it would be: DateTime.Parse(txtDate.Text);
var selectedDate = new DateTime(2017, 1, 16);
// Count how many holidays there are within 3 days from the selcted date.
var count = holidays.Count(holiday => holiday - selectedDate <= TimeSpan.FromDays(3));
// Then add the count and 3 to the selected date
var closingDate = selectedDate.AddDays(count + 3);
// Now we have to make sure the closing date is not a holiday.
if (count > 0)
{
int skipDays = 0;
while (holidays.Any(holiday => holiday == closingDate.AddDays(skipDays)))
{
// holidays list contains the date. Skip it.
skipDays++;
}
closingDate = closingDate.AddDays(skipDays);
}
I have a calendar and a textbox that contains a time of day. I want to create a datetime that is the combination of the two. I know I can do it by looking at the hours and mintues and then adding these to the calendar DateTime, but this seems rather messy.
Is there a better way?
You can use the DateTime.Add() method to add the time to the date.
DateTime date = DateTime.Now;
TimeSpan time = new TimeSpan(36, 0, 0, 0);
DateTime combined = date.Add(time);
Console.WriteLine("{0:dddd}", combined);
You can also create your timespan by parsing a String, if that is what you need to do.
Alternatively, you could look at using other controls. You didn't mention if you are using winforms, wpf or asp.net, but there are various date and time picker controls that support selection of both date and time.
If you are using two DateTime objects, one to store the date the other the time, you could do the following:
var date = new DateTime(2016,6,28);
var time = new DateTime(1,1,1,13,13,13);
var combinedDateTime = date.AddTicks(time.TimeOfDay.Ticks);
An example of this can be found here
Depending on how you format (and validate!) the date entered in the textbox, you can do this:
TimeSpan time;
if (TimeSpan.TryParse(textboxTime.Text, out time))
{
// calendarDate is the DateTime value of the calendar control
calendarDate = calendarDate.Add(time);
}
else
{
// notify user about wrong date format
}
Note that TimeSpan.TryParse expects the string to be in the 'hh:mm' format (optional seconds).
Using https://github.com/FluentDateTime/FluentDateTime
DateTime dateTime = DateTime.Now;
DateTime combined = dateTime + 36.Hours();
Console.WriteLine(combined);
DateTime newDateTime = dtReceived.Value.Date.Add(TimeSpan.Parse(dtReceivedTime.Value.ToShortTimeString()));
Combine both. The Date-Time-Picker does support picking time, too.
You just have to change the Format-Property and maybe the CustomFormat-Property.
I have a masked text box that is used to show today's date, like this:
txtDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
However it can still be edited to change the date. Being a masked text box, the only worry is if someone wants to add the date like so:
27/1/15
Is there a way I can edit this to add the additional information and automatically format it to this? Possibly using String.Format perhaps?
27/01/2015
EDIT: To clarify, When the form opens, the txtDate will automatically receive today's date, but if a user wants to change the date, how can I ensure that the date will remain in the right format? I.e. dd/MM/yyyy.
try something like this
DateTime d = DateTime.Now;
string str = String.Format("{0:00}/{1:00}/{2:0000}", d.Month, d.Day, d.Year);
Edit:
You can add days, months, years... to your variable of type DateTime d
Example:
d = DateTime.Now;
d = d.AddDays(5); // add 5 days to current date
EDIT2
Say you have 3 textBoxes txtDays, txtMonth and txtYear
int year = Convert.ToInt32(txtYear.Text);
int month = Convert.ToInt32(txtMonth.Text);
int days = Convert.ToInt32(txtDays.Text);
// you can assign any date as follows:
DateTime d = new DateTime(year, month, days);
Or if the users will have only one textBox called txtDate and they have to enter the date in the form "MM/dd/yyyy":
var[] date = txtDate.Split('/');
txtDate.Text = String.Format("{0:00}/{1:00}/{2:0000}", date[0], date[1], date[2]);
I'm using Visual C# 2010 Express to create a Form that has the user choose a type of car(compact, standard, luxury) and a date on the calendar for how long they are going to rent it. I can't seem to figure out how to calculate the amount of days to find the total cost.
I tried NumberDays = (Calendar.SelectionEnd - Calendar.SelectionStart);
but I get an error "Cannot implicitly convert type 'SystemTimeSpan' to 'int'"
I also tried to make today's date being the start date and a selection on the calendar being the end date but I'm not sure how to calculate the total days for that either.
Any help would be very much appreciated.
Use
NumberDays = (Calendar.SelectionEnd - Calendar.SelectionStart).TotalDays;
DateTime dt1 = DateTime.Parse("5/1/2011");
DateTime dt2 = DateTime.Parse("5/14/2011");
private void button1_Click(object sender, EventArgs e)
{
int NumberDays = (int) dt2.Subtract(dt1).TotalDays;
MessageBox.Show(NumberDays.ToString());
}