DatePickerDialog "month" keeps starting on 0 (Xamarin Android C#) - c#

I used DatePickerDialog in a fragment. I have a Button and an unclickable EditText. Whenever the user presses the button, it shows the DatePickerDialog, but the problem is when it chooses January, the value of the month is 0.
This is my code
DatePickerDialog datePickerDialog = new DatePickerDialog(this.Activity, this, year, month, day);
datePickerDialog.Show();
this.year = year;
this.month = month + 1;
this.day = dayOfMonth;
eventdatesetText.EditText.Text = month + "/" + dayOfMonth + "/" + year;
Is my code right? Do I need to add something more on this code?
this.month = month + 1;
I have added + 1 but for some reason it is not working. Any solution? Thank you for future answers! I appreciate it a lot! :)

At first, you use this.month = month + 1;, so the code should be eventdatesetText.EditText.Text = this.month + "/" + dayOfMonth + "/" + year;.
Or you can try to use eventdatesetText.EditText.Text = (month+1) + "/" + dayOfMonth + "/" + year;.
In addition, you can try to custom a DatePickerDialog to show the month value. You can check my answer in the link.

In the line that contains eventdatesetText.EditText.Text =, you should be using this.month instead of month.
As per your code, month is the 0-indexed month number, and you made this.month into the 1-indexed month number by doing a simple +1 on it.
Since you want to use the 1-indexed month number, you should be using this.month.
Adjusted:
DatePickerDialog datePickerDialog = new DatePickerDialog(this.Activity, this, year, month, day);
datePickerDialog.Show();
this.year = year;
this.month = month + 1;
this.day = dayOfMonth;
eventdatesetText.EditText.Text = this.month + "/" + this.day + "/" + this.year;

Have you tried upgrading to dotNet MAUI? I think this should be different there!

Related

how to fix string was not recognized as a valid DateTime

See the end of this message for details on invoking
just-in-time (JIT) debugging instead of this dialog box.
************** Exception Text **************
System.FormatException: String was not recognized as a valid DateTime.
at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles)
at System.Convert.ToDateTime(String value)
at ExtraTutoManager.Dashcont.CulcPay(DateTime dateAf) in D:\coure du soire gestion\visual studio project\ExtraTutoManager\ExtraTutoManage
declaration global
public DateTime rendVous;
public DateTime temp;
I want to covert string to datetime by ToDateTime() , in my project VS running without any problem but in another pc this String was not recognized as a valid DateTime
temp = Convert.ToDateTime("" + dateAf.Date.Day + "/" + (DateTime.Now.Month + 1) + "/" + DateTime.Now.Year);
this is my method
//Culcs
public DateTime Culcdate(DateTime dateAf)
{
int mont = DateTime.Now.Month - dateAf.Date.Month;
if (DateTime.Now.Month == dateAf.Date.Month)
{
temp = Convert.ToDateTime("" + dateAf.Date.Day + "/" + (DateTime.Now.Month + 1) + "/" + DateTime.Now.Year);
}
else if (mont - (mont - 1) >= 1 && DateTime.Now.Day >= dateAf.Date.Day)
{
temp = Convert.ToDateTime("" + dateAf.Date.Day + "/" + (DateTime.Now.Month + 1) + "/" + DateTime.Now.Year);
}
else if (mont - (mont - 1) >= 1)
{
temp = Convert.ToDateTime("" + dateAf.Date.Day + "/" + DateTime.Now.Month + "/" + DateTime.Now.Year);
}
return rendVous = temp;
}
The reason is failed in other computers is likely to be they have different Cultures, one computer could be trying to parse in American format MM/dd/yyyy and the other one is in dd/MM/yyyy.
You can use DateTime.ParseExact() and specify the format and culture you are trying to parse.
https://learn.microsoft.com/en-us/dotnet/api/system.datetime.parseexact?view=net-6.0
DateTime.ParseExact(temp, "dd/MM/yyyy", CultureInfo.InvariantCulture)
Convert.ToDateTime will take into account the current systems Culture and thus expects the string to be in a certain format.
See more info here:
https://learn.microsoft.com/en-us/dotnet/api/system.convert.todatetime?view=net-6.0#System_Convert_ToDateTime_System_String_System_IFormatProvider_
To make this code work on the other system, you could change the system language used, but a better solution is to make sure that the input value is in the current cultures format, or use the second parameter for Convert.ToDateTime() which is an IFormatProvider to tell the system which culture to use. That way it will not matter anymore what system runs the code.
In your case you could also write:
temp = new DateTime(DateTime.Now.Year, DateTime.Now.Month + 1, dateAf.Date.Day)
instead of
temp = Convert.ToDateTime("" + dateAf.Date.Day + "/" + (DateTime.Now.Month + 1) + "/" + DateTime.Now.Year);
to avoid the date parsing all together. Make sure to not do this when the month is december as that would still result in an invalid datetime.
If you are simply trying to achieve getting the current DateTime + 1 month you could do this:
temp = DateTime.Now.AddMonths(1);
which will also work when the current date is in december, and will result in a date in januari the next year.

How to create a custom year with different months?

I want to make a year as 1 April to 31 March with c#. If a Person input his DOB, the year changes if cross 31 March.`
//Display Window Period
DateTime winst21 = new DateTime(DateTime.Now.Year, dob.Month, dob.Day);
DateTime wind21 = winst21.AddYears(1);
Label2.Text = "Your Current IPPT Window is " + " " + winst21.ToString("dd/MM/yyy") + " " + "-" + " " + wind21.ToString("dd/MM/yyy");
I guess you just an offset of +9 or -3 months:
//Display Window Period
DateTime winst21 = new DateTime(dob.AddMonths(9).Year, dob.Month, dob.Day);
DateTime wind21 = winst21.AddYears(1);

Unity C#, How to addition X days to a date?

In this part of code sDate show current date 2016/11/16, Now what is best way to add 7 days to current date? for example if current date is 2016/11/29 + 7 change to 2016/12/06. I'm looking for a way to addition an int value to a date.
string Year;
string Month;
string Day;
float time;
string sDate;
void Start ()
{
Year = System.DateTime.Now.Year.ToString();
Month = System.DateTime.Now.Month.ToString();
Day = System.DateTime.Now.Day.ToString();
int Y = int.Parse (Year);
int M = int.Parse (Month);
int D = int.Parse (Day);
if (Y >= 2016 & M >= 11 & D >= 21)
{
sDate = Year + "/" + Month + "/" + Day + " | Expired";
Debug.Log (sDate);
Application.Quit ();
}
else
{
sDate = Year + "/" + Month + "/" + Day + " | Working";
Debug.Log ("System date: " + sDate);
}
}
All you need to do is use the standard DateTime function AddDays:
DateTime result = original.AddDays(n);
where original is the original date and n is the number of days you want to add.
I'd also check the rest of the documentation on the DateTime structure as there are a lot simpler ways of doing what you are trying here. As mentioned in the comments you can construct a DateTime object from it's components:
DateTime referenceDate = new DateTime(2016, 11, 15);
and then do comparisons on that:
if (testDate >= referenceDate)
{
// Do something
}
etc.

Convert format of datetime to another format of datetime

My code parses a raw data and turns it into a datetime string format such as below
string birthday = "20" + year + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + second;
So birthday is a string and then I converted it to datetime format such as below
DateTime bdaylater= Convert.ToDateTime(birthday);
The result became like the one below
7/8/2015 5:02:05 AM
in which I wanted to convert to something like the one below
2015/07/08 05:02:05.000
How can I achieve such result.
Thanks.
You should format your date variable before printing the same
string birthday = "2015" + "-" + "07" + "-" + "08" + " " + "05" + ":" + "02" + ":" + "05";
DateTime bdaylater= Convert.ToDateTime(birthday);
Console.WriteLine(bdaylater.ToString("yyyy/MM/dd hh:mm:ss.mmm"));
this will give the o/p 2015/07/08 05:02:05.02
Fiddle example
If you want only 000 in millisecond the string will be "yyyy/MM/dd hh:mm:ss.000"
Would you like to convert it to string format? With 3 zeros padded on it? Maybe this could help:
int year = 15;
int month = 7;
int day = 8;
int hour = 5;
int minutes = 2;
int second = 5;
string birthday = "20" + year + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + second;
DateTime bdaylater = Convert.ToDateTime(birthday);
Console.WriteLine(bdaylater);
Console.WriteLine(bdaylater.ToString("yyyy/MM/dd hh:mm:ss.000")); //2015/07/08 05:02:05.000
Console.ReadLine();
Try this:
DateTime.Parse(birthday).ToString("yyyy/MM/dd hh:mm:ss.fff")

How do I represent date range for months that donot have 31 days in c#?

I want to find the leaves taken by an employee in a month.
The code works perfectly for all the dates.
Now, if I want to find the leaves taken by the employee in January, the range is:
DateTime first = Convert.ToDateTime(DateTime.Now.Month + "01" + DateTime.Now.Year);
DateTime end = Convert.ToDateTime(DateTime.Now.Month + "31" + DateTime.Now.Year);
The problem is that some months do not have 31 days. Is there an easy way with which I could assign the variables From and To the range. An error would be given when the months's Feburary or April because they donot have 31 days.
The code for executing the search is :
returnedRows = LeaveDS.Tables["Leave"].Select("LeaveDate >= #" + first + "# AND LeaveDate <= #" + end + "#");
You could do something like this:
DateTime end = first.AddMonths(1).AddDays(-1);
DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month)
it'll give you the days in a month.
Use DateTime.DaysInMonth(int year, int month)
int days = DateTime.DaysInMonth(2012, 2);
int days2 = DateTime.DaysInMonth(2011, 2);
output:
days = 29
days2 = 28
You can get the number of days in a month by DateTime.DaysInMonth(year,month), and use this as basis for your query.
The alternative is to use the first of each month but alter your select query to be less than the end date.
DateTime first = Convert.ToDateTime(DateTime.Now.Month + "01" + DateTime.Now.Year);
DateTime end = first.AddMonths(1); // Becomes 01 of next month
returnedRows = LeaveDS.Tables["Leave"].Select("LeaveDate >= #" + first + "# AND LeaveDate < #" + end + "#");
There is a great method to get the days in a month, it's called DateTime.DaysInMonth
DateTime end = new DateTime(first.Year, first.Month, DateTime.DaysInMonth(first.Year, first.Month);
var enddate = DateTime.Now.AddMonths(1);
DateTime end = new DateTime(enddate.Year,enddate.Month,1);
By the way, if you're using .NET 3.5 or greater Linq-To-DataSet will simplify and improve the code:
int month = 2; // f.e. for february
var currentCalendar = System.Globalization.CultureInfo.CurrentCulture.Calendar;
int daysInMonth = currentCalendar.GetDaysInMonth(month);
DateTime start = new DateTime(DateTime.Now.Year, month, 1);
DateTime end = new DateTime(DateTime.Now.Year, month, daysInMonth);
var filteredRows = LeaveDS.Tables["Leave"].AsEnumerable()
.Where(r => r.Field<DateTime>("LeaveDate").Date >= start
&& r.Field<DateTime>("LeaveDate").Date <= end );
// use ToArray for an array, CopyToDataTable for a DataTable etc.

Categories