How to get the selected date of a MonthCalendar control in C# - 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

Related

Getting first and last date of selected month c# winforms

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);

I want to retrieve the current date and time nox textBox

protected void ButtonPesquisar_Click(object sender, EventArgs e)
{
var macroController = new MacroController();
var itens = macroController.ObterTodos(new Entities.FiltroMacro()
{
//NumeroLocomotiva = TextBoxNumeroLocomotiva.Text,
DataInicio = DateTime.Parse(TextBoxDataInicio.Text + " " + TextBoxHoraInicio.Text),
DataFim = DateTime.Parse(TextBoxDataFim.Text + " " + TextBoxHoraFim.Text)
my code now works as follows: inform the values ​​in textBox and returns me what is posted. But I'm wanting to return the current date and time of the system without I need to fill.
This is very simple, you could have just Googled this.
TextBoxHora.Text = DateTime.Today.ToString("g"); // Just the time
TextBoxData.Text = DateTime.Today.ToString("D"); // Just the Date
TextBoxDataHora.Text = DateTime.Today.ToString(); // Complete date and Time
TextBoxDataHoraCompleta.Text = DateTime.Now;
Go to these links for more information.
Link
Link
In the code I saw that you want the get the date from the text boxes, so: If you want to parse the date time and provide the format in one string you should use the DateTime.ParseExact method. For instance, see the usage in a sample console application:
static void Main(string[] args)
{
var parsedDate = DateTime.ParseExact("2014$05$01", "yyyy$MM$dd", DateTimeFormatInfo.CurrentInfo);
Console.WriteLine("Year: {0}",parsedDate.Year);
Console.WriteLine("Month: {0}",parsedDate.Month);
Console.WriteLine("Day: {0}",parsedDate.Day);
Console.ReadLine();
}
You can read Standard Date and Time Format Strings at msdn for searching more information about the date formats.

How to limit or filter input in Mask TextBox in Windows application

Update: Edited my question for better understanding I hope
I set my Mask TextBox properties to shortdate MM/DD/YYYY or 00/00/0000 but it can accept month more than 12 and date more than 31. How can I filter month only to 12 and date only to 31?
^([012]\d|30|31)/(0\d|10|11|12)/\d{4}$
use above regular expression in your overridden control.
Tried a work around for this problem so here it is. Mine is inputting the user's birthdate month cannot be higher than 12 and year must be less than today's year (haven't solved on how to accept current year.
private void Form1_Load(object sender, EventArgs e)
{
maskedTextBox1.Mask = "00/00/0000";
maskedTextBox1.ValidatingType = typeof(System.DateTime);
maskedTextBox1.TypeValidationCompleted += new TypeValidationEventHandler(maskedTextBox1_TypeValidationCompleted);
}
void maskedTextBox1_TypeValidationCompleted(object sender, TypeValidationEventArgs e)
{
if (!e.IsValidInput)
{
MessageBox.Show("The data you supplied must be a valid date in the format mm/dd/yyyy.");
}
else
{
DateTime userDate = (DateTime)e.ReturnValue;
if (userDate >= DateTime.Now)
{
MessageBox.Show("The date in this field must be less or equal than today's date.");
e.Cancel = true;
}
}
}

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;

C# program crash

I'm trying to get my first ever C# application working as intended. :)
This application is a time converter, which allows user to input numbers into six different text boxes. For example, user puts 2009 into yyyy.Text, 20 into dd.Text, 02 into M.text, 02 into hh.Text, 49 into mm.Text and 35 into ss.Text. Then the program converts the numbers into a hexadecimal string.
For example,
2009 20 02 02:49:35 -> 63370694975000000 -> E1234FB3278DC0
private void button1_Click(object sender, EventArgs e)
{
String dateString = yyyy.Text + dd.Text + M.Text + hh.Text + mm.Text + ss.Text;
DateTime timestamp = DateTime.ParseExact(dateString, "yyyy dd M hh:mm:ss", CultureInfo.CurrentCulture);
long ticks = timestamp.Ticks;
long microseconds = ticks / 10;
convertedText.Text = microseconds.ToString("X");
}
The application is compiled fine, but after putting numbers into the text boxes and clicking the 'Convert' button, the program crashes. The error: Additional information: String was not recognized as a valid DateTime.
Am I using the wrong DataTime format? or something? :(
Thanks in advance... I wanna get this working :)
I think you need spaces and colons as you declare in the format.
When making the dateString, don't forget to insert spaces.
Use
String.Format("{0} {1} {2} {3}:{4}:{5}",yyyy.Text, dd.Text, M.Text, hh.Text, mm.Text, ss.Text)
And, place a try-catch block - it's the easiest way to catch exceptions when converting, (although not recommended for a good program), in case the user inputs some insane numbers and text.
Your dateString does not correspond to the format you specified - you have a string without any separators (like spaces or colons). Format the string accordingly to your format. Also, it is always a good idea to use format utils. But I think you should use string, not String:
string dateString = string.Format("{0} {1} {2} {3}:{4}:{5}",
yyyy.Text, dd.Text, M.Text, hh.Text, mm.Text, ss.Text);
Try to insert a breakpoint on the DateTime timestamp = DateTime.ParseExact(dateString, "yyyy dd M hh:mm:ss", CultureInfo.CurrentCulture) line.
Then before you execute that command, hover your mouse over dateString. Then I think you will see that dateString does nto match the format you have provided to ParseExact at all.
When the string matches the format you have given, it should work fine.
Good luck! :)
Try this
Solution 1:
private void button1_Click(object sender, EventArgs e)
{
DateTime timestamp = new DateTime(
Convert.ToInt32(yyyy.Text)
, Convert.ToInt32(M.Text)
, Convert.ToInt32(dd.Text)
, Convert.ToInt32(hh.Text)
, Convert.ToInt32(mm.Text)
, Convert.ToInt32(ss.Text));
long ticks = timestamp.Ticks;
long microseconds = ticks / 10;
convertedText.Text = microseconds.ToString("X");
}
Solution 2:
private void button1_Click(object sender, EventArgs e)
{
string dateString = string.Format("{0}/{1}/{2} {3}:{4}:{5}", M.Text,dd.Text,yyyy.Text, hh.Text, mm.Text, ss.Text);
long ticks = Convert.ToDateTime(dateString).Ticks;
long microseconds = ticks / 10;
convertedText.Text = microseconds.ToString("X");
}
Output:
E1234FB3278DC0

Categories