how to fix string was not recognized as a valid DateTime - c#

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.

Related

DatePickerDialog "month" keeps starting on 0 (Xamarin Android 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!

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

Why does NodaTime.LocalDate.MinIsoValue have a year "9999"

The static property NodaTime.LocalDate.MinIsoValue has the value 9999-01-01 whereas I'd have expected it to have the same value as default(LocalDate) which is 0001-01-01. Is there a reason for this value or is it a bug?
I'm using NodaTime version 2.4.4.
Formatting local date using pattern "yy" or "yyyy" outputs years of era not the year which is -9998 in this case. LocalDate.MinIsoValue is from BCE era. The format you have used didn't include era in it. You can use "g" or "gg" in your custom format to include the era.
var def = default(LocalDate);
var min = LocalDate.MinIsoValue;
Console.WriteLine("def: " + def.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
Console.WriteLine("def with era: " + def.ToString("yyyy-MM-dd gg", CultureInfo.InvariantCulture));
Console.WriteLine("def.Year: " + def.Year);
Console.WriteLine("def.YearOfEra: " + def.YearOfEra);
Console.WriteLine("min: " + min.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
Console.WriteLine("min with era: " + min.ToString("yyyy-MM-dd gg", CultureInfo.InvariantCulture));
Console.WriteLine("min.Year: " + min.Year);
Console.WriteLine("min.YearOfEra: " + min.YearOfEra);
Console.WriteLine("min < def: " + (min < def));
def: 0001-01-01
def with era: 0001-01-01 A.D.
def.Year: 1
def.YearOfEra: 1
min: 9999-01-01
min with era: 9999-01-01 B.C.
min.Year: -9998
min.YearOfEra: 9999
min < def: True

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

Categories