String was not recognized as valid DateTime c# - c#

Why this line won't work?
DateTime myDate = DateTime.ParseExact("04:05:14:17:17:09", "DD:MM:YY:HH:MM:SS", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.NoCurrentDateDefault);

This format is very much not what you're trying to do.
Try changing it to dd:MM:yy:HH:mm:ss:
DateTime myDate = DateTime.ParseExact("04:05:14:17:17:09", "dd:MM:yy:HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.NoCurrentDateDefault);
So, what have I changed:
MM refers to months, mm is for minutes
ss needs to be lowercase
dd needs to be lowercase
yy needs to be lowercase
And just for the record, I left HH uppercase because that means it's 24-hour, but lowercase would be 12 hour.
You might want to review the Custom Date and Time Format Strings MSDN page, where all these are explained. It has some good examples that might help you.

Related

Date was not recognized as a valid DateTime

kinda got an issue that I cant solve right now.
I've got a discord bot running on my raspberry pi, which has a system for automated messages that are sent after a certain amount of time, or an exact date, has passed.
My code works on Windows when debugging there, but the console throws a warning on Linux when running the published project.
The date is taken from a table in my MySQL database and put into a DataTable. The code that grabs the date from the DataRow is:
DateTime datetime = DateTime.ParseExact(row["datetime"].ToString(), "dd.MM.yyyy HH:mm:ss", CultureInfo.InvariantCulture);
Why is it happening? No matter how I format the string (dots, dashes or slashes), the warning persists. The messages are not sent.
I even tried removing invisible whitespaces with regex, doesnt work either.
(The regex in question, though I scrapped it since it yielded no fruit anyways)
Regex.Replace($"{row["datetime"].ToString()}", #"[^\d\s\.:]", string.Empty);
If RDBMS type is DateTime then why should we convert to string and then parse it back to DateTime? Let's do it direct:
DateTime datetime = Convert.ToDateTime(row["datetime"]);
and let .net convert boxed DateTime (row["datetime"] is of type object?) to DateTime
There are a couple issues--at the highest level, your ParseExact method is encountering a Date Time string that does not match the supplied format.
According to the code you posted, the expected format of is dd.MM.yyyy HH:mm:ss, and in your exception exception, shows a Date time string (8/2/2021 2:00:00 PM) that does not match:
contains / and your expected format has .
dd is a 2-digit day, but the input date time string only has single digit days
MM expects a two digit month and the input date time only has a single digit month
the string contains AM/PM, and your format neglects to account for that.
Finally it's not clear if your date format is Month Day Year, or Day Month year.
The second issue, is that ParseExact should be enclosed in a try/catch block, so that your code can handle the case when an unexpected formatted date time string is passed in, and not crash.
To solve this, wrap your call into a try/catch, and gracefully handle the FormatException
And then make sure the Format string matches the expected input string.
Here is the .NET reference for the various DateTime format tokens
The error message is letting you know the issue.
You have :
DateTime datetime = DateTime.ParseExact(row["datetime"].ToString(), "dd.MM.yyyy HH:mm:ss", CultureInfo.InvariantCulture);
Notable, you are saying that the date format is going to be "dd.MM.yyyy HH:mm:ss"
Then your error message is saying that you couldn't parse :
8/2/2021 2:00:00 PM
Which is essentially a format of "d/M/yyyy h:mm:ss tt" (Assuming that days come before months).
If you change your code to :
DateTime datetime = DateTime.ParseExact(row["datetime"].ToString(), "d/M/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
You should be good to go. DateTime.ParseExact does what it says on the tin, it parses the date format exactly how you say it should come. If you aren't sure you can use DateTime.Parse() (But you can occassionally run into issues where days/months are around the wrong way).
Tested using the following code :
var myDateString = "8/2/2021 2:00:00 PM";
DateTime datetime = DateTime.ParseExact(myDateString, "d/M/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
Console.WriteLine(datetime.ToString());

want to convert datetime to format like mm/yyyy

I want to grab the datetime object in string form such as "mm/yyyy"
ViewBag.Created = d.item.StartDate.ToString("mm/yyyy");
but I am getting string as 10-2012. Please help me to overcome this issue.
Format for month, should be in MM, mm is for minutes
ViewBag.Created = d.item.StartDate.ToString("MM/yyyy",
CultureInfo.InvariantCulture);
mm is minutes, and / is the culture-specific date separator. It sounds like in the current culture, - is the date separator. I suspect you want MM/yyyy, using the invariant culture, which has / as the separator:
ViewBag.Created = d.item.StartDate.ToString("MM/yyyy",
CultureInfo.InvariantCulture);
Alternatively, you could just quote the slash:
ViewBag.Created = d.item.StartDate.ToString("MM'/'yyyy");
Note that this difference can also change the month and year figures, if the current culture uses a non-Gregorian calendar.
See the MSDN page on custom date and time format specifiers for more details.
Are you certain that you want to fix the format for all cultures though? It's unfortunate that there's no way of saying "give me a culture-appropriate month-and-year format" but you at least need to be aware that it might look odd to some people.
you can use
ViewBag.Created = d.item.StartDate.ToString(#"MM\/yyyy");

Date format pattern

Setting format for the date
#String.Format("{0:D}", Model.Date)
Code above shows the date in the following format: (13 January 2012)
The required output: (Friday 13 January 2012)
Is there a format for this pattern?
Yep, here you go.
String.Format("{0:dddd d MMMM yyyy}", Model.Date)
Full MSDN Documentation
The general rule I use to remember these formats is like this:
one character means the number alone;
two characters means add a leading zero if necessary
three characters means use three letters if day or month, four numbers for year
four letters means use full word for day or month
Extra stuff (not special characters) just gets put in the string
e.g. Consider 1st Jan 2001
String.Format("{0:(d;dd;ddd;dddd),(M;MM;MMM;MMMM),(y,yy,yyy,yyyy)}", DateTime.Parse("2001/01/01"))
will return
(1;01;Mon;Monday),(1;01;Jan;January),(1,01,2001,2001)
Similar rules for times, like this:
String.Format("{0:(h;hh):(m;mm):(s,ss) (t,tt)}", DateTime.Now)
to give this:
(9;09):(41;41):(34,34) (P,PM)
DateTime now = DateTime.Now;
Console.WriteLine(String.Format("{0:dddd d MMMM yyyy}",now));
//output = Friday 13 January 2012
if you want the standard date format just use
Console.WriteLine(now.ToString("D"));
here is something I wrote real quick as well to help you in the future if you want to see what you can to with the now.ToString() in regards to passing formats.
try this out in a Console Application to see the results.. Cheers
DateTime now = DateTime.Now;
Console.WriteLine(now.ToString("d"));
Console.WriteLine(now.ToString("D"));
Console.WriteLine(now.ToString("f"));
Console.WriteLine(now.ToString("F"));
Console.WriteLine(now.ToString("g"));
Console.WriteLine(now.ToString("G"));
Console.WriteLine(now.ToString("m"));
Console.WriteLine(now.ToString("M"));
Console.WriteLine(now.ToString("o"));
Console.WriteLine(now.ToString("O"));
Console.WriteLine(now.ToString("s"));
Console.WriteLine(now.ToString("t"));
Console.WriteLine(now.ToString("T"));
Console.WriteLine(now.ToString("u"));
Console.WriteLine(now.ToString("U"));
Console.WriteLine(now.ToString("y"));
Console.WriteLine(now.ToString("Y"));
Console.Read();
As #Dommer points out String.Format("{0:dddd d MMMM yyyy}", Model.Date) gives you the result you want. And here you'll find MSDN documentation on date and time formats.
If you need to be culturally-aware then use Format(IFormatProvider, String, Object()).
String.Format(CultureInfo.InvariantCulture, "{0:D}", Model.Date);

DateTime formats C#

I have a string which needs to be converted and validated to a DateTime. The string is in the following format 'dd.mm.yy'
I am trying to convert it to DateTime using the following
string format = "dd.mm.yy";
date = DateTime.ParseExact(current.Substring(aiRule.AiLength), format,
CultureInfo.InvariantCulture);
but unfortunately this fails.
The question is how to convert a string in the format 'dd.mm.yy' to a DateTime ?
Thank you
mm means "minutes". I suspect you want "dd.MM.yy". See MSDN for more information about custom date and time format strings.
(In particular, read the part about the "yy" specifier and how it chooses which century to use. If you can possibly change the input to use a four digit year, that could save you some problems...)
the string format should be like this....
string Format = "dd.MM.yy"
mm is for showing minutes
MM is for showing months..
I hope it will helps you...
As earlier posts has already pointed out, mm means minutes and MM means months. I ran this test snippet and it works as expected:
string format = "dd.MM.yy";
string date = "27.10.11";
DateTime result;
result = DateTime.ParseExact(date, format, CultureInfo.InvariantCulture);
I'll tell something "heretical". If dd.MM.yy (with 2 or 4 yy) is the format of your local culture, then you could let the DateTime.Parse (not ParseExact!) do its work without setting it to CultureInfo.InvariantCulture, or perhaps setting it to your local culture like new CultureInfo("it-IT").

Trying to parse a DateTime in C#

I am trying to parse a DateTime in C# and have the following lines of code:
string dt =Convert.ToString( DateTime.FromFileTime(e8.sts[counter8].TimeStamp));
string format = "dd-MM-yyyy HH:mm:ss";
DateTime dateTime = DateTime.ParseExact(dt, format,CultureInfo.InvariantCulture);
When I debug dt is coming in as 05/18/2011 09:25:17 AM but I get an expection saying:
String was not recognized as a valid
DateTime.
Starting off, you have no need for the conversion.
DateTime.FromFileTime(e8.sts[counter8].TimeStamp) returns a DateTime already...
Even so, with the string you have provided, DateTime.Parse(str) will take care of you.
If you end up storing this value in a text file, and really are dead-set on using a custom format string to parse it (which you don't need to):
The format you have:
Day/Month/Year 24-hour:minute:second
But looking at your input date:
05/18/2011 09:25:17 AM
You want:
Month/Day/Year 12-hour:minutes:seconds AM/PM
The format for what you want is:
MM/dd/yyyy hh:mm:ss tt
Isn't this expected? Date 05/18/2011 09:25:17 AM doesn't match your format string dd-MM-yyyy HH:mm:ss. Your date is in format MM/dd/yyyy HH:mm:ss tt.
Try this:
DateTime dateTime = DateTime.Parse("05/18/2011 09:25:17 AM");
I don't see any reason for the conversion. Just use:
DateTime.FromFileTime(e8.sts[counter8].TimeStamp)
Your DateTime is coming in as MM-dd-yyyy but you are trying to parse it as dd-MM-yyyy
Change your format string to "MM-dd-yyyy HH:mm:ss tt"
You can tell this as dt, using your current format string, is trying to be parsed as the 5th day (dd) of the 18th month (MM) of 2011 (yyyy)...
EDIT:
Sorry, I completely missed the AM/PM designator, you need the tt part of the format string. This will handle the AM/PM part of the string
EDIT 2:
As per your most recent comment, you want to convert it into MM-dd-yyyy HH:mm:ss string, the all you need to do is:
var outputString = DateTime.FromFileTime(e8.sts[counter8].TimeStamp).ToString("MM-dd-yyyy HH:mm:ss");
You already have the TimeStamp in a val;id .NET DateTime object, so all you need to do is perform a .ToString() with the required time format.
DateTime parsed = DateTime.ParseExact(dt,"MM/dd/yyyy HH:mm:ss tt",CultureInfo.InvariantCulture);
s many of the others have explained here, the format needs to be changed. However even when I tried the formats they have suggested, I still received the same error that you did. Eventually I hit upon the right format to get successful results.
The format should be:
string format = "MM/dd/yyyy HH:mm:ss tt";
because you are specifying time pattern such as AM. If the month is given as single digit, eg: 5, then MM should be replaced with M. I used slash instead of hypen between the dates because that's how the original date had been given.

Categories