Getting first and last date of selected month c# winforms - c#

before getting started I want to tell that I already know how to select the 1st and last date of the current month. But, my question is different, I want to select the 1st and the last date of the selected month using date-time picker in c# winforms.
public Form1()
{
InitializeComponent();
MonthYearDT();
}
private string MonthYearDT()
{
dTMY.Format = DateTimePickerFormat.Custom;
dTMY.CustomFormat = "yyyy-MM-dd";
dTMY.ShowUpDown = true; // to prevent the calendar from being displayed
return dTMY.Value.ToString("yyyy-MM-dd");
}
private void BtnExecute_Click(object sender, EventArgs e)
{
.
.
.
.
monthYear = MonthYearDT();
.
.
.
}
In the above, the value of monthYear is 2019-12-19. It can be changed to any month. I want to get the 1st 2019-12-01 and last date 2019-12-31 of the selected month.
How can I do this?
Any help would be highly appreciated.

Before doing anything firstly change the function MonthYearDT() from string to DateTime
private DateTime MonthYearDT()
{
dTMY.Format = DateTimePickerFormat.Custom;
dTMY.CustomFormat = "yyyy-MM";
dTMY.ShowUpDown = true; // to prevent the calendar from being displayed
dTMY.Enabled = false;
return dTMY.Value;
}
Getting the first is easy. Just create a new DateTime like so
DateTime selectedDate = MonthYearDT();
var first = new DateTime(selectedDate.Year, selectedDate.Month, 1);
getting the second is just as easy. Use first, add one month and subtract one day like so
var second = first.AddMonths(1).AddDays(-1);
firstDate = first.ToString("yyyy-MM-dd");
lastDate = second.ToString("yyyy-MM-dd");

Universal truth is that the first day of any month would always be same.
And to get the last date below DateTime function can be used. You need year also along the month to get the last day
var lastDay = DateTime.DaysInMonth(year, month);
var lastDayDate = new DateTime(year, month, lastDay);

Related

Error for converting some specific date in persian calendar format

We have website that everybody can add a record witch includes date column
everytime the add a record to database a date will save in date column
and when they want to see them in a gridview, it will be convert in persian calendar format
The problem is that some specific dates can not convert.for example if we want to convert date 1398/6/31 to Gregorian date, It will give an error
protected void Page_Load(object sender, EventArgs e)
{
System.DateTime date = System.DateTime.Today;
System.Globalization.PersianCalendar p = new
System.Globalization.PersianCalendar();
int year = p.GetYear(date);
int month = p.GetMonth(date);
int day = p.GetDayOfMonth(date);
System.DateTime currentDate = new System.DateTime(1398, 6, 31);
azsh.Text = currentDate.ToString("d/M/yyyy");
}
Year, Month, and Day parameters describe an unrepresentable DateTime.

Get dates by month in C# Windows Phone 7

The following code displays a list of appointments scheduled for a specific date in my windows phone 7 app
private void DisplayAppointmentsForDate(DateTime date)
{
appointmentsSource.FetchData(date, date.AddDays(1));
this.AppointmentsList.ItemsSource = appointmentsSource.GetAppointments((IAppointment appointment) =>
{
DateTime currentAppointmentStart = appointment.StartDate;
DateTime currentAppointmentEnd = appointment.EndDate;
DateTime requiredAppointmentsStartDate = date.Date;
DateTime requiredAppointmentsEndDate = date.Date.AddDays(1);
if (requiredAppointmentsEndDate > currentAppointmentStart && requiredAppointmentsStartDate < currentAppointmentEnd)
{
return true;
}
return false;
});
}
private void RadCalendar_SelectedValueChanged(object sender, ValueChangedEventArgs<object> e)
{
if (e.NewValue == null)
{
this.AppointmentsList.ItemsSource = null;
return;
}
DisplayAppointmentsForDate((e.NewValue as DateTime?).Value);
}
But this shows the appointments scheduled for a specific date. EG. If 23/09/2013 is selected on the calendar, then the list would display all the appointments on that day.
I want to change this so that the list displays all appointments for a particular month. EG. If the calendar is on the month of July 2013, the the list should show all appointments in that month.
The Start and End Dates are all set to DateTime type with values such as 23/09/2013 12:01PM, and this is how it is used to get list of apps.
I've tried using appointmentsSource.FetchData(date.Month, date.AddDays(1));, but it doesn't work.
How do I do this?
I'm assuming that the method FetchData takes a "start date" parameter and an "end date parameter", in which case, you just need to get the first date of the current month and the last date of the current month
var currentDate = DateTime.Now; // Or whatever date you want to displa
var startDate = new DateTime(currentDate.Year, currentDate.Month, 1);
var endDate = new DateTime(currentDate.Year, currentDate.Month, DateTime.DaysInMonth(currentDate.Year, currentDate.Month));
appointmentsSource.FetchData(startDate, endDate);
if your FetchData takes a month parameter and the number of days, then
appointmentsSource.FetchData(currentDate.Month, DateTime.DaysInMonth(currentDate.Year, currentDate.Month));
we really need to see the "FetchData" method to be able to provide you with a definitive answer

How to change "ddd" datetime format to a number view

I want to make that code to show me a current datetime on my pc clock when i click a button... i did it with that code listed down. But here is my question how can i make the "ddd" (day of a week) to be shown in number, not in words, I mean:
00-sunday
01-monday
and etc. ...
This is my code for the button:
private void SetClock_Click(object sender, EventArgs e)
{
SetClock.Click += new EventHandler(SetClock_Click);
{
DateTime time = DateTime.Now;
string format = "yy-MM-dd-ddd-hh-mm-ss";
txtSend.Text = time.ToString(format);
}
}
What i have to add to make it. Thanks
txtSend.Text = string.Format("{0:yy-MM-dd}-{1:00}-{0:hh-mm-ss}", time, (int)time.DayOfWeek);
A format isn't required, you can just cast DayOfWeek to an int:
var dayAsInt = (int)DateTime.Now.DayOfWeek;
Looking at the Custom Date and Time Format Strings page, there doesn't appear to be a format string for it :-(
The following should do it:
txtSend.Text =
time.ToString("yy-MM-dd-") +
((int)time.DayOfWeek).ToString("00") +
time.ToString("-hh-mm-ss");
You could use this to get the day of week numeric
int dayofweek = (int)DateTime.Now.DayOfWeek;

How to delete data from selected Date to current Date using DateTimePicker

My problem is to delete data from given date to current date,
My code works fine for deleting the data by the date given in the DateTimePicker.
i want to delete the data from given date in DateTimePicker to CurrentDate.
For example:
In subfolder123 the data is available from 20100131 to 20110531 (Date Format yyyyMMdd).
I want to delete the date from 20100215 to 20110531.
Hope you understood my Question and problem.
Is there any suggestions?
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
string todaysDate = dateTimePicker1.Text;
int FinalDate4 = 0;
string Destinationnsefx = "C:\\folder\\subfolder\\subfolder123";
int xyz = 0;
string SecSym = (9722).ToString();
MWriterClass writerdelete1 = new MWriterClass();
try
{
writerdelete1.OpenDirectory(Destinationnsefx);
writerdelete1.OpenSecurityBySymbol(SecSym);
FinalDate4 = int.Parse(todaysDate);
if (writerdelete1.get_bDateExists(FinalDate4))
{
try
{
writerdelete1.DeleteIntradaySecRecordEx(FinalDate4, 080000, 240000);
}
catch
{
}
}
writerdelete1.CloseSecurity();
writerdelete1.CloseDirectory();
}
catch
{
}
}
Thanks in advance.
It sounds like you get a date from your DateTime picker and you need to work from that start date to your end date, correct?
In that case, look at the AddDays method for a DateTime object.
For example, this snippet of code will start at 4/1/2011 and print every date from then until today, in the format you specified.
var workingDate = new DateTime(2011, 4, 1);
while (workingDate < DateTime.Today)
{
workingDate = workingDate.AddDays(1);
Console.WriteLine(string.Format("{0:yyyyMMdd}", workingDate));
}

How to get the selected date of a MonthCalendar control in C#

How to get the selected date of a MonthCalendar control in C# (Window forms)
"Just set the MaxSelectionCount to 1 so that users cannot select more than one day. Then in the SelectionRange.Start.ToString(). There is nothing available to show the selection of only one day." - Justin Etheredge
From here.
I just noticed that if you do:
monthCalendar1.SelectionRange.Start.ToShortDateString()
you will get only the date (e.g. 1/25/2014) from a MonthCalendar control.
It's opposite to:
monthCalendar1.SelectionRange.Start.ToString()
//The OUTPUT will be (e.g. 1/25/2014 12:00:00 AM)
Because these MonthCalendar properties are of type DateTime. See the msdn and the methods available to convert to a String representation. Also this may help to convert from a String to a DateTime object where applicable.
Using SelectionRange you will get the Start and End date.
private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
var startDate = monthCalendar1.SelectionRange.Start.ToString("dd MMM yyyy");
var endDate = monthCalendar1.SelectionRange.End.ToString("dd MMM yyyy");
}
If you want to update the maximum number of days that can be selected, then set MaxSelectionCount property. The default is 7.
// Only allow 21 days to be selected at the same time.
monthCalendar1.MaxSelectionCount = 21;
For those who are still trying, this link helped me out, too; it just puts it all together:
http://dotnetslackers.com/VB_NET/re-36138_How_To_Get_Selected_Date_from_MonthCalendar_control.aspx
private void MonthCalendar1_DateChanged(object sender, System.Windows.Forms.DateRangeEventArgs e)
{
//Display the dates for selected range
Label1.Text = "Dates Selected from :" + (MonthCalendar1.SelectionRange.Start() + " to " + MonthCalendar1.SelectionRange.End);
//To display single selected of date
//MonthCalendar1.MaxSelectionCount = 1;
//To display single selected of date use MonthCalendar1.SelectionRange.Start/ MonthCalendarSelectionRange.End
Label2.Text = "Date Selected :" + MonthCalendar1.SelectionRange.Start;
}
It'll be helpful if you want just to convert it by:
String myCalendar = monthCalendar1.SelectionRange.Start.ToShortDateString()
But if you want to get a formatted output you could instead:
String myCalendar = monthCalendar1.SelectionRange.Start.ToString("yyyy-MM-dd")
It's important to use year and day as lower caps, and month as upper or else it'll return you a wrong format, for example, if you do:
String myCalendar = monthCalendar1.SelectionRange.Start.ToString("YYYY-MM-DD")
it will return: YYYY-07-DD (If the original date's month was July)
private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
string clickeddate = monthCalendar1.SelectionRange.Start.ToString("dddd, dd MMM yyyy");
richTextBox.AppendText(clickeddate); //or whatever you decide to do with it.
}
SelectionRange property

Categories