Populating month and day - c#

I'm populating a combobox with month name as follows:`
var engCulture = new CultureInfo("en-US");
cmbAmCul.Items.AddRange(engCulture.DateTimeFormat.MonthNames);
what is the right way to:
eliminate the blank entry after the
12 month names.
populate another
combobox with day (1-31 || 1-28 ||
1-30) according to the month
selected?

For the first part, you could use a linq query...
var engCulture = new CultureInfo("en-US");
cmbAmCul.Items.AddRange(from m in engCulture.DateTimeFormat.MonthNames
where !String.IsNullOrEmpty(m)
select m);
The DateTimeInfo class supports calendars with 13 months, which is why this occurs.
For the second part, I would go for something like...
for (int i = 1; i <= DateTime.DaysInMonth(year, month); i++) {
cmbDay.Items.Add(i.ToString());
}
Obviously populating the year/month vars from your selected values.

Use String.Trim() to remove blanks from beginning & end of strings
Use return value from DateTime.DaysInMonth(int year, int month) to populate your day combo box
You could also use a DateTime picker from the standard controls or is it not an option for you?

You don't specify what you are trying to build (ASP.NET or Winforms etc) but you could possibly use a Calendar control instead of dropdowns to improve the User experience. Less clicks and less code tho go wrong perhaps.

Related

Remove Blackout Dates from WPF Calendar Blackout Date Collection

So I wanted to Blackout all dates from 2000 from present in the WPF Calendar that aren't in a Datetime list.
My thought was to blackout all dates individually from 2000 to now and then remove each date from the blackout Date Collection.
This Code adds dates fine but it doesn't work to remove the dates from the collection.
var DateList = FI.Select(x => x.LastWriteTime.Date).Distinct().ToList();
for (var day = new DateTime(2000,1,1); day.Date <= DateTime.Now.Date; day = day.AddDays(1))
{
Calendar.BlackoutDates.Add(new CalendarDateRange(day));
}
foreach (DateTime k in Datelist)
{
Calendar.BlackoutDates.Remove(new CalendarDateRange(k));
}
I compared the date range from the blackout date collection and the newly created one from the current iteration of the list but it says they aren't equivalent.
Comparison seen here
Thank you for the assistance.
CalendarDateRange class lets you specify a start date and end date for the range, you don't have to add a CalendarDateRange for every day.
https://msdn.microsoft.com/en-us/library/system.windows.controls.calendardaterange(v=vs.110).aspx
Also, there are a lot of code examples on the Calendar.BlackoutDates documentation :
https://msdn.microsoft.com/en-us/library/system.windows.controls.calendar.blackoutdates(v=vs.110).aspx
var DateList = FI.Select(x => x.LastWriteTime.Date).Distinct().ToList();
//Add all dates between DateTime.MinValue and the day before your DateList min value.
Calendar.BlackoutDates.Add(new CalendarDateRange(DateTime.MinValue, DateList.Min().AddDays(-1)));
** EDIT **
After reading your comment, it seems that I've misunderstood your issue. You're trying to remove a new instance of CalendarDateRange, which is different than the CalendarDateRange instance that was added to the collection, even though they have the same start and end values.
Replace your foreach block with this one to fix your issue :
foreach (var k in DateList)
{
while (Calendar.BlackoutDates.Any(bd => bd.Start.Date == k.Date))
{
Calendar.BlackoutDates.Remove(Calendar.BlackoutDates.FirstOrDefault(bd => bd.Start.Date == k.Date));
}
}

how to find date range between two dates in days format using linq c#

I have a requirement for generating report in form of 15 days,30 days,45 days.
I have to compare the list data which is coming from db with current date.example if difference is 5days. It is less than 15,so i should send to 15 days ,if >15 i should send to greater than 15etc.How to write linq query for this.can any one help on this please
I'm not sure that can be possible to make this in only one query.
But, I can propose you another solution.
Instead of one query, you can use one query for every case.
In order to compare date difference, you can use SqlFunctions Class.
For this, you should use :
using System.Data.Objects.SqlClient;
Here is the query for 5 days with an imaginary table and fields :
var lstDiff5 = (from ro in dc.Commandes where
SqlFunctions.DateDiff("DD", ro.Cmd_PromisDate, DateTime.Now) <= 5
select ro).ToList();
The DateDiff Function takes the date part (DD for days), the start date and the end date. In my case the start date is the current date.
And for 15 days :
var lstDiff15 = (from ro in dc.Commandes where
SqlFunctions.DateDiff("DD", ro.Cmd_PromisDate, DateTime.Now) > 5 &&
SqlFunctions.DateDiff("DD", ro.Cmd_PromisDate, DateTime.Now) >= 15
select ro).ToList();
You can change the operators > et >= depending your need.
At the end, you can fill your report using all of your lists or you can merge your lists into a new list in order to bind your report to your final list.
You can use DaysBetween function in linq.It will return all dates betwee the given dates.
Example:
DateTime dt = DateTime.Today.Date.AddMonths(1);
int d = dt.DaysBetween(DateTime.Today).ToList().Count;

check if number of days has passed since a date

I am trying to check if a certain number of days has passed since a date and if it has then change the color of the grid row.
So if the date is 12/11/2016 and I want to check if 10 days has passed since that date.
if (dt.Date > dt.Date.AddDays(10))
{
e.Item.Style.Add("background-color", "#C400F9");
break;
}
So adding 10 days to the 12th would be the 22/11/2016 and since today is the 23/11/2016 that means 10 days has passed. But all rows in the grid are changing to the color. Do I need to add another if statement to compare the date + the days passed to today's date?
Did you mean to use today's date? If so, that's DateTime.Now:
if (DateTime.Now > dt.Date.AddDays(10))
At the moment you are comparing dt.Date against same date plus 10 days - as others noted, this will never be met.
Update. As Tim suggests in comments, using DateTime.Today might be more appropriate.
DateTime d1;
DateTime d2;
if((d1 - d2).TotalDays == 10)
{
//some code
}
Your problem is in your comparison. You're trying to figure out if dt is bigger than dt + 10. Obviously it will never be true.
Your comparison will never be true, it's like doing:
If (10 > 10 + 10)...
What you want to do is compare 10 days after the date with today using DateTime.Now
Can you Try this, Below X is date that you want to compare with(it may come form db or hardcoded date)
if (X > dt.Date.AddDays(10))
{
e.Row.Attributes.Add("background-color", "#C400F9");
}
if (DateTime.Now.Date> dt.Date.AddDays(10).Date)
{
e.Item.Style.Add("background-color", "#C400F9");
break;
}
if (DateTime.Now.Date > dt.Date.AddDays(10))
{
}

Populate date according to month and year selected in dropdown list

I have 3 dropdown list each for year, month and date.
Now I want to populate my dates according to year and month selected by the user. I want to try it using normal dropdown list, so I'm ruling out the option of datetime picker for the time being.
This is my code which i'm using normally to fill the values:
protected void Call_Date()
{
for (int i = 1; i <= 31; i++)
{
date0.Items.Add(i.ToString());
}
for (int j = 1; j <= 12; j++)
{
month0.Items.Add(j.ToString());
}
for (int k = DateTime.Now.Year; k <= 2020; k++)
{
year0.Items.Add(k.ToString());
}
}
What can I do to make it work accordingly?
Try this;
DateTime myDate = new DateTime((int)year0.SelectedValue,(int)month0.SelectedValue,(int)date0.SelectedValue)
But remember there is a issue that #Cris as raised.
You can check whether the year is leap by using DateTime.IsLeapYear method. If you dont want to use DateTime function, then you can calculate leap year like this. Once that is found, then finding number of days in a month is easy.
Jan. 31,
Feb. 28/29(leap year),
Mar. 31,
Apr. 30,
May 31,
Jun. 30,
Jul. 31,
Aug. 31,
Sep. 30,
Oct. 31,
Nov. 30,
Dec. 31
here is a sample example for you http://dotnetstation.wordpress.com/adding-date-year-and-month-in-dropdownlist-using-aspnetc/
You should leverage the frameworks's DateTime class to get the dates that you need from the selected Year and Month.
//build a date for the month and year selected by the user
DateTime newDate = new DateTime(yearSelected, monthSelected, 1);
//iterate through the days in that month
for (int i = newDate.Day; i < DateTime.DaysInMonth(newDate.Year, newDate.Month); i++ )
{
//add to your list
}
Not sure if a Client-side solution would be okay, but it looks like you may be able to use Knockout as one option... It kinda looks like this example: http://knockoutjs.com/examples/cartEditor.html, where depending on the first dropdown (Month), you can populate the next (day) and have it match up the valid amount of days so you can generate a valid date...
Having said that, I recently made an editor template for a birthdate field... It is about the same setup as you, with three dropdowns. It also has a hidden field (the actual date) that is set using Javascript that is run every time one of the three dropdownboxes changes. It then tries to set the value of the hidden field and run Unobtrusive Validation on the field to check for a valid date and show an errormessage if not...
Pseudo-code that checks the dropdowns in the editor template is here:
$("Dropdown").change(function () {
if (($("Year").val() != "") && ($("Day").val() != "") && ($("Month").val() != "")) {
var date = new Date($("Year").val(), $("Month").val() - 1, $("Day").val())
$("Hidden").val(date.toString("yyyy-MM-dd"));
$('form').validate().element('Hidden');
} else {
$("Hidden").val("");
}
}
})
Lastly as Cris said, you also need to check the date for a valid date and not Feb 31th. Serverside, I would just do a Date.TryParse() on the date to check if it is an actual date and not or something when the form gets posted...

How to show the Birthdate in mm/dd/yyyy format if year is separated from it?

I have a modalpopup inside it I have checkboxes,when I check the checkboxes and save the changes there is a dynamically created table with dynamically generated labels.I have a checkbox Birthdate inside the modal popup which shows the mm/dd only.And another checkbox below it that will show the year only, and will be visible if Birthdate checkbox is checked.
I want to show that if Birthdate checkbox is checked and the save button is clicked then insisde the dynamic table it will show the mm/dd only.And if year checkbox is checked ,and the save button is clicked, then it will show the Birthdate inside the dynamically created table as mm/dd/year.
seems like there's multiple questions here - not sure which one(s) you're asking.
1) how to format a date in format X or Y?
- You can use String.Format("{0:MM/dd}", yourDateTime) or yourDateTime.ToString("MM/dd") or whatever for that case. Add on /yyyy for the other case.
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
2) how to conditionally display format?
- various ways, but a simple one that I think would work fine is to just add into Page_Load the check, so something like: string format = cond ? "MM/dd/yyyy" : "MM/dd"; and then checkbox.Text = yourDateTime.ToString(format);
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.checkbox.text.aspx
3) how to get the display to change on checkbox change?
- #2 combined with adding AutoPostBack=true on your checkbox(es)
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.checkbox.autopostback.aspx
If you can further clarify the question, in particular what parts of what you're trying to do you're having trouble with, it may help us provide better answers :)
if (!Convert.IsDBNull(oReader["BIRTH_DATE"]))
{
DateTime dt = Convert.ToDateTime(oReader["BIRTH_DATE"]);
int date = dt.Day;
DateTime bd = Convert.ToDateTime(oReader["BIRTH_DATE"]);
int month = bd.Month;
lblBirthDate.Text += date + "/" + month;
DateTime dob = Convert.ToDateTime(oReader["BIRTH_DATE"]);
int year = dob.Year;
lblBirthYear.Text += year;
}

Categories