Problems with a DateTime - c#

I´ve been trying to add some lines of a .csv document to a SQL Database ,but in a point i get this exception:
SYSTEM.FORMATEXCEPTION: STRING '0000-00-00 00:00:01' WAS NOT RECOGNIZED AS A VALID DATETIME.
AT SYSTEM.DATETIMEPARSE.PARSE(READONLYSPAN`1 S, DATETIMEFORMATINFO DTFI, DATETIMESTYLES STYLES)
AT SYSTEM.DATETIME.PARSE(STRING S)
AT FRAME2020.OBJETOSERVICIOS.DEVOLVERSERVICIOS(STRING[] LISTA) IN
D:\TRABAJO\FRAME2020\FRAME2020\CONEXIONBDD.CS:LINE
And i dont know how to solve it , i tried with try/except but it doesnt work with my approach ,any recommendations?

Problem is in your date which you try to set: 0000-00-00 00:00:01, there isn't day 0, month 0 and year 0.
Minimal DateTime is 1-1-0001 00:00:00

You haven't showed us any code, so I'm making some assumptions here. It looks like you're using DateTime.Parse to parse a column in your csv source that you expect to be a DateTime. However, your source has values in that column which do not parse into a valid DateTime. Such as 0000-00-00 00:00:01.
Others have already pointed out that 0000-00-00 00:00:01 is not a valid DateTime. In order to address this issue, you can use a different method to parse that column. For example, DateTime.TryParse. This will attempt to parse a string into a DateTime and return false if it fails or true if it succeeds.
string s = "0000-00-00 00:00:01";
if (!DateTime.TryParse(s, out DateTime dt))
{
// The string could not be parsed to a DateTime.
}
else
{
// The string was successfully parsed and the variable dt will have the parsed
// DateTime.
}
Then once you have that, you'll know if you successfully parsed the string into a DateTime and you can do something other than throw a FormatException when it fails.

Related

Not able to convert the datetime stored as a string to Datetime within a IList

I'm working on an WebApi which receives the data from database using Lambda and storing in a IList. The output I'm getting has a dataformat as "2018-04-20T14:39:20.01". But I want to show the date format as "20-Apr-2018 / 02:39:20 PM".
Once i get the output, I'm manipulated the date and converted to the format which I wanted that are stored as a string.
Now when I'm trying to send that data back to the IList, am getting error saying that the String is not recognized as a valid datetime.
string val = statusSourceType1[0].updatedDate.Value.ToString("dd-MMM-yyyy hh:mm:ss tt").ToString();
#1
statusSourceType1[0].updatedDate = DateTime.Parse(val);
#2
statusSourceType1[0].updatedDate = DateTime.ParseExact(val, "dd-MMM-yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
#3
statusSourceType1[0].updatedDate = DateTime.ParseExact(val, "dd-MMM-yyyy hh:mm:ss tt", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces);
In the above code, first line converts the dateformat from 2018-04-20T14:39:20.01 to 15-Apr-2018 12:23:21 PM.
Once the conversion is done, I want to convert the string value into datatime and pass with the output since my UI is expecting the datetime and not string.
While converting the string to datetime, either Am getting the runtime error "String is not recognized as a valid datetime" or the datetime format gets back to its original state.
Please help me with this.
"...datetime stored as a string..."
There's your problem right there.
You are working in a WebApi and your UI is expecting a DateTime, not a string. So why do you bother to convert the date to string and back?
DateTime does not have a display format - only string representations of it does.
Just send the UI an instance of the DateTime struct and let the UI handle the display format - that's the UI's responsibility, not the server.
try setting culture if you need
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
then try
dt.ToString("dd/MMMM/yyyy"); //or whichever
As your comment. Answer simple question, if you set 1112018 as date using ddmmyyyy how can you expect to get the conversion working back to datatime. You app design is not right, let the View do the formatting and pass the dt obj
OR
make you View to expect string version of dt

Error converting DateTime to string format yyyy-MM-dd

I'm trying to convert some DateTime values to string format yyyy-MM-dd. The problem is i only need the date but in my case model.StartDate contains both date and time. When declaring model.StartDate as string "start" looks like this: 4/1/2014 12:00:00 AM. I get this error when trying to parse:
System.FormatException was unhandled by user code Message=String was
not recognized as a valid DateTime.
My best guess is that the error occurs because string contains both Date and Time but i could be wrong. If i explore model.StartDate further i can also find Day, DayOfTheWeek etc. Is this the right approach? I just want to convert model.StartDate to string "start" with format yyyy-MM-dd.
Heres my code:
string start = model.StartDate.ToString();
model.StartDate = DateTime.ParseExact(start, "yyyy-MM-dd", CultureInfo.InvariantCulture);
string end = model.EndDate.ToString();
model.EndDate = DateTime.ParseExact(end, "yyyy-MM-dd", CultureInfo.InvariantCulture);
Dunno what the problem is, might be that start contains time? I have no idea.
The model.StartDate and model.EndDate are DateTime properties from the view model:
[NopResourceDisplayName("Admin.GAStatistics.GAStatistics.StartDate")]
[UIHint("DateNullable")]
public DateTime? StartDate { get; set; }
[NopResourceDisplayName("Admin.GAStatistics.GAStatistics.EndDate")]
[UIHint("DateNullable")]
public DateTime? EndDate { get; set; }
EDIT:
Iv'e uploaded a image here showing the actual output i'm getting in the debugger:
https://imageshack.com/i/1n51u2p
Thank you
You are converting the dates to string but you don't specify the format. Try
string start = model.StartDate.ToString("yyyy-MM-dd);
ToString() uses the current thread's Culture format to convert the date to a string, including the time. The format used is G, the general date and time format.
Just for this format, you don't need to specify CultureInfo.InvariantCulture because there isn't anything culture specific. A common gotcha with the yyyy/MM/dd format though is that some cultures use - as the date specifier, and / is the date placeholder. In such a case you would have to use:
string start = model.StartDate.ToString("yyyy-MM-dd,CultureInfo.InvariantCulture);
UPDATE
From the comments, it seems that model.StartDate and model.EndDate are not DateTime objects but strings with a specific format that include a time element.
What you are actually trying to do is parse the original string to a DateTime object, then format this object to the new format string:
var date=DateTime.ParseExact(model.StartDate,"M/d/YYYY HH:mm:ss tt",
CultureInfo.InvariantCulture);
model.StartDate=date.ToString("yyyy-MM-dd",CultureInfo.InvariantCulture);
assuming the string the value "4/1/2014 12:00:00 AM" for April 1, 2014
You appear to be misunderstanding how ParseExact works (or actually what it does). Parsing, in general, is the process of taking data of type X and converting it to type Y - in the context of DateTime this means converting a date string to a DateTime instance. This is completely different to what you are trying to do which is formatting a DateTime instance.
Given you already have the date you don't need to parse anything, all you need to do is format the date
model.StartDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
CultureInfo.InvariantCulture is important when working with fixed formats because you want to make sure you aren't culture aware i.e. the format you specify is exactly how you want it to display in all cultures.
Use the .Date property of a DateTime to get only the Date part. Your ToString() will also yield different results based on the current culture meaning that while your ToString() and then TryParse might work for you right now, it will break in other countries.
You can use ToString() overload to specify a specific format. Different formats can be found here

Format Exception - string not recognized as a valid DateTime

I have an issue similar to this > Format exception String was not recognized as a valid DateTime
However, my spec requires a date format of ddMMyyyy, therefore I have modified my code but I am still getting the same error
DateTime now = DateTime.Now;
DateTime dt = DateTime.ParseExact(now.ToString(), #"ddMMyyyy", CultureInfo.InvariantCulture);
I am unclear why.
You code fails because you are attempting to parse a date in the format ddMMyyyy, when by default DateTime.ToString() will produce a format with both date and time in the current culture.
For myself in Australia that would be dd/MM/yyy hh:mm:ss p e.g. 11/10/2013 11:07:03 AM
You must realise is that the DateTime object actually stores a date as individual components (e.g. day, month, year) that only needs to be format when you output the value into whatever format you desire.
E.g.
DateTime now = DateTime.Now;
string formattedDate = now.ToString("ddMMyyyy", DateTimeFormatInfo.InvariantInfo);
For more information see the api doc:
http://msdn.microsoft.com/en-us/library/8tfzyc64.aspx
For ParseExact to work, the string coming in must match exactly the pattern matching. In the other question you mentioned, the text was coming from a web form where the format was specified to be exactly one format.
In your case you generated the date using DateTime.Now.ToString() which will not be in the format ddMMyyyy. If you want to make the date round trip, you need to specify the format both places:
DateTime now = DateTime.Now;
DateTime dt = DateTime.ParseExact(now.ToString("ddMMyyyy"), #"ddMMyyyy", CultureInfo.InvariantCulture);
Debug your code and look at what the result of now.ToString() is, it's is not in the format of "ddMMyyyy", which is why the parse is failing. If you want to output now as a string in the ddMMyyy format, then try now.ToSTring("ddMMyyyy") instead.
now.ToString() does not return a string formatted in that way. Try using now.ToString("ddMMyyyy").
You might be better off testing with a static string like "30041999"

Convert.DateTime

What Convert.DateTime will convert the date 7/25/2010 12:00:00 it's current format is(MM/dd/yyyy HH:mm:ss)?
When I convert this string format to date time I am getting the error "string was not recognized as valid DateTime"
None. Dates are not stored internally as a certain format.
If you want to parse a string into a date, use DateTime.ParseExact or DateTime.TryParseExact (the former will throw an exception if the conversion fails, the second uses an out parameter):
DateTime myDate = DateTime.ParseExact("7/25/2010 12:00:00",
"MM/dd/yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
If you want to display a certain format, use ToString with the format string.
So, if you have a date object that represents midday of the 25th of July 2010 (doesn't matter how it is represented internally) and you want to format it with the format string "MM/dd/yyyy HH:mm:ss" you do the following:
string formattedDate = myDate.ToString("MM/dd/yyyy HH:mm:ss");
If you need to use Convert.DateTime, I'll assume you're working with a string you want to convert to a date. So you might try this:
DateTime date = Convert.DateTime("7/25/2010 12:00:00 am");
string formattedDateString = date.ToString("MM/dd/yyyy HH:mm:ss")
I'm making no assumptions as to why you'd want to do this, except that, well, you have your reasons.
DateTime.TryParse() or DateTime.Parse() will do the trick.
Edit: This is assuming that you are going from a string to a DateTime object.
Edit2: I just tested this with your input string, and I receive no error with DateTime.Parse

converting string representation of a date and time to the System.DateTime

DateTime dt;
bool diditParse = DateTime.TryParse("17/06/2000 12:00:00 AM", CultureInfo.CreateSpecificCulture("en-US"), DateTimeStyles.AssumeLocal, out dt);
diditParse is returning false because it is expecting a format MM/DD/YYYY which differs from what I have DD/MM/YYYY
I am not sure what culture/styles or what needs to be do to get the try parse working?
If you look at the example given here http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx
you can just use:
bool diditParse = DateTime.TryParse("17/06/2000 12:00:00 AM", out dt);
Unless your looking for something more indepth you shouldn't need to use the culture/styles part.
Your trying to use http://msdn.microsoft.com/en-us/library/9h21f14e.aspx
public static bool TryParse(
string s,
IFormatProvider provider,
DateTimeStyles styles,
out DateTime result
)
Parameters
s
Type: System.String
A string containing a date and time to convert.
provider
Type: System.IFormatProvider
An object that supplies culture-specific formatting information about s.
styles
Type: System.Globalization.DateTimeStyles
A bitwise combination of enumeration values that defines how to interpret the parsed date in relation to the current time zone or the current date. A typical value to specify is None.
result
Type: System.DateTime%
When this method returns, contains the DateTime value equivalent to the date and time contained in s, if the conversion succeeded, or MinValue if the conversion failed. The conversion fails if the s parameter is null, is an empty string (""), or does not contain a valid string representation of a date and time. This parameter is passed uni
If you know that the string is in DD/MM/YY format, then you can use TryParseExact.
Try using DateTime.TryParseExact()
It appears to allow you to tell it what date format to expect.
Try...
("fr-FR")
although any European or other culture which represents dates in that fashion should work.
Try "en-GB" we list our dates DD-MM-YY, instead of MM-DD-YY like they do in the US.

Categories