Format text in a Masked TextBox - c#

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

Related

0 Character Problem in the beggining DateTime

I got every part of date in the code that you can see below. But the problem is if we consider today's date I need day and month as 02 not as 2.
I need that 0 char in the beggining. How can I manage it?
DateTime dategift = DateTime.Now;
var year = dategift.Year.ToString();
var month = dategift.Month.ToString();
var day = dategift.Day.ToString();
var hour = dategift.Hour.ToString();
var min = dategift.Minute.ToString();
var sec = dategift.Second.ToString();
use the Zero placeholder
string day = dategift.Day.ToString("00");
or the "dd" custom format specifier
string day = dategift.ToString("dd");
If you're wanting to format the date, you can do so without pulling out all the various values as strings.
Something like:
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

How to get from datetimepicker only the separated values of the date?

How do I get from datetimepicker only the separated values of the date?
For example, for this date (6,5,2017) I want to get--> day=5 , month=6, year=2017.
DateTimePicker value is type DateTime which has properties day, month, year.
To access them:
dateTimePicker1.Value.Day;
dateTimePicker1.Value.Month;
dateTimePicker1.Value.Year;
These properties are read only. To modify it use methods:
Edit (thx to #Richard): AddDays, AddMonths, AddYears methods return new DateTime value that you have to assign back to DateTimePicker.Value
dateTimePicker1.Value = dateTimePicker1.Value.AddDays(_days);
dateTimePicker1.Value = dateTimePicker1.Value.AddMonths(_months);
dateTimePicker1.Value = dateTimePicker1.Value.AddYears(_years);

How to set default month and day in the datetimepicker?

I have searched online and i only managed to find codes to set the year month and day.
dateTimePicker2.Value = new DateTime(2017,12,31);
I tried using the custom format and it does not seem to work
dateTimePicker2.CustomFormat = "DD/MM";
dateTimePicker2.Value = new DateTime(12,31);
You cannot create DateTime object only from day and month. DateTime simply doesn't have this kind of constructor. DateTime Constructors
So you need to go with some kind of "workaround"
- Use "dummy" year and when you need to use a date - use only Month and Day properties.
var dummyYear = 2000;
dateTimePicker2.Value = new DateTime(dummyYear, 12, 31);
Another workaround will be to use ParseExact method which will create DateTime based on the format you are using "dd/MM"
var date = DateTime.ParseExact("31/12", "dd/MM", CultureInfo.InvariantCulture);
dateTimePicker2.Value = date; // 12/31/2017
Notice that when you did not provide a year - current year will be used.
Another notice: DD is invalid format for days it should be lower case "dd"
You cannot partially set the date without a year, it's not valid.
What you cand do is specify the month and date in code as "default" values, and get the current year programmtically (or whatever year you want), and use that value for the year.
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "dd/MM";
dateTimePicker1.Value = DateTime.Now;

Get yesterday's date from the date entered

I have console application that accepts date as parameter. However, the date is passed as a string in this format:
string dt = DateTime.Now.ToString("yyyyMMdd");
Once the date is entered I need to programmatically get day - 1 from the entered date. Since this is a string, I cannot do any calculation.
For example, user enters:
20141023
I need to subtract a day from the date to get:
20141022
I did a quick fix to solve my immediate need, however, this is not the right way to do it and it has a bug:
int yt = Int32.Parse(dt) - 1;
And then I turn around and convert it yt.ToString()
The above solution will not work if it's the 1st of the month.
Is there a way I can programmatically get yesterday's date in the format (yyyyMMdd) without changing the format and possibly not using the TimeSpan?
Why don't parse the input into a DateTime object? Then you can use the DateTime.AddDays(-1)
For example:
var inputDate = DateTime.ParseExact("20141022", "yyyyMMdd", CultureInfo.InvariantCulture); // change "20141022" into the inputted value
var yesterday = inputDate.AddDays(-1);
var yesterdayString = yesterday.ToString("yyyyMMdd"); // this will be yesterdays date, in the string format
Try this...
DateTime data = DateTime.ParseExact("20141023", "yyyyMMdd", CultureInfo.InvariantCulture);
Console.WriteLine("{0} - {1}", data, data.AddDays(-1).ToString("yyyyMMdd"));
Would this work for you ?
string newDateTimeStr = (DateTime.Today.AddDays(-1)).ToString("yyyyMMdd");
EDIT:
for the date entered by the user:
string txtInputDate = Console.ReadLine();
DateTime dateTime = new DateTime(txtInputDate).ToLocalTime();
string newDateTimeStr = (dateTime.AddDays(-1)).ToString("yyyyMMdd");

How do I subtract a number of years from a user-supplied year value

I have a text field that will contain a given year, for example, "2011". I need to calculate the value of the year 70 years earlier.
I have this code already, which supplies a default value for the text box:
var LastYear = DateTime.Now.AddYears(-1).ToString("yyyy"); //"2011"
Yeartextbox.Text = LastYear;
The user is allowed to change the value of the text box to whatever year they want. I need to take the data from the text box, and calculate 70 years earlier. For example, if the text box contains "2011" I need the result of 1941; if the user enters 2000 I need the result of 1930.
What is stopping from you to read from the Textbox and Assign to a DateTime object and call the AddYears function ?
DateTime dateEntered=DateTime.Parse(Yeartextbox.Text);
var thatYear= dateEntered.AddYears(-70);
Yeartextbox.Text = thatYear.ToShortDateString();
You are storing a year into the text box, not a date. Just, for example, 2011. That's just a number, an integer, and you can do integer math on it. (The fact that it happens to be a year is irrelevant to the - operator.)
If you want to subtract 70 years from that, just do 2011 - 70:
var year = Int32.Parse(Yeartextbox.Text) - 70;
I'm not sure I understand....but is this what you're looking for....pre-poluting the text box with -70?
var LastYear = DateTime.Now.AddYears(-70).ToString("yyyy"); //"2011"
Yeartextbox.Text = LastYear;
Assuming you have two text boxes, here's how to do it:
// Get year as an integer from the text box
int currentYearAsInt = int.Parse(txtCurrentYear.Text);
// Create DateTime out of it (January 1st 1984, for example)
DateTime currentYear = new DateTime(currentYearAsInt, 1, 1);
// Create new DateTime 70 years older (remember, you cannot just call AddYears on the object, you have to assign returned value)
DateTime oldYear = currentYear.AddYears(-70);
// Populate new text box with old year's value (or do whatever you want with it
txtOldYear.Text = oldYear.Year.ToString();
Hope it helps.
For instance if they want this year, its going to be 2012-70
If i understand you correctly, you have problems to translate the year from the user to a DateTime object.
So if the user entered f.e 2005 you want 1935-01-01. Am i right?
This would work:
var input = "2005"; // Yeartextbox.Text
int year = 0;
DateTime result;
if(int.TryParse(input, out year))
{
result = new DateTime(year, 1, 1).AddYears(-70); //1935-01-01
}
string initialYear = "2011";
int year;
string calculatedYear;
if (int.TryParse(initialYear, out year))
{
var initialDate = new DateTime(year, 1, 1);
calculatedYear = initialDate.AddYears(-70).Year.ToString();
}
else
{
// Handle error since no valid value was entered
}
This will do the work (you obviously need to adapt it to your code). If it doesn't you might need to assure that the screen is correctly refreshed.

Categories

Resources