string "3/21/2013" is not recognized as valid datetime - c#

I am trying to convert a string to a datetime format in C#.
DateTime SnapDate = Convert.ToDateTime(valid(odr, 4)).Date;
protected string valid(OleDbDataReader myreader, int stval)//if any columns are found null then they are replaced by zero
{
object val = myreader[stval];
if (val != DBNull.Value)
return val.ToString();
else
return Convert.ToString("");
}
And it gives me the following error: "The string was not recognized as a valid DateTime. There is a unknown word starting at index 0."
I tried several things like: parse and parseExact but still didn't get it.
I am reading this data from an excel sheet.

Looks like your input string is in en-US format. Try specifying CultureInfo object into Parse method:
DateTime SnapDate = DateTime.Parse(valid(odr, 4), new CultureInfo("en-US")).Date;
It will force Parse method to look for date in M/d/yyyy format, which is valid for your input string of 3/21/2013.

I'd say rather than using your system culture or choosing one, pick the exact date format and use that, like:
DateTime dt = DateTime.ParseExact("3/21/2013", "M\\/d\\/yyyy", null);
No ambiguity on the order of parameters, or on the date separator.
FYI: The reason I use a backslash before the forward-slash is to escape the forward-slash - forward-slash means date separator, not necessarily the forward-slash, so escaping it removes any possible ambiguity.

Related

Use correctly String.Format - C#

I have two objects of type string, where I retrieve a date in dd/MM/yyyy format, I need to format this date I'm getting to show only month and year, in order to use this object in a groupby to group records by month. I'm doing it as follows, retrieving the date in another object to apply the formatting:
//Object where I retrieve the date with dd/MM/yyyy normally
public string DataCupom { get; set; }
//Object where I retrieve the value of DataCupom and I'm trying to apply the formatting
public string DataCupomAgrupadoMes { get { return String.Format("{MM:yyyy}", DataCupom); }
How can I apply String.Format correctly to retrieve only month and year?
A string is just a sequence of characters. It has no "date" or "time" semantics. Thus, attempting to format a sequence of characters (sucha as the DataCupom string) like it being some data type representing dates or time is not going to work.
In your case, one of the simplest approaches would probably be splitting the DataCupom string using '/' as separator, and then assemble the new required string from those parts of the split which represent month and year.
var parts = DataCupom.Split('/');
return $"{parts[1]}:{parts[2]}";
You can try parsing dateString to DateTime and then format.
DateTime dateTime = DateTime.Parse(dateString);
dateTime.ToString("MM/yyyy");
String.Format() uses numeric placeholders:
return String.Format("{0:MMyyyy}", DataCupom);
Where the 0 in the format string means to look at the first additional argument position for the value.
You can also use interpolation:
return $"{DataCupom:MMyyyy}";
or a simple ToString() call:
return DataCupom.ToString("MM:yyyy");

Datetime parse not working for specific format

Hello experts i am not able to parse the datetime object from following format
2019-12-04T04:26:29:00
in c#. When I trying to parse this format I'll get
04-12-2019 04:26:29
Without T as DateTime object
You can use the ToString() function in the following way to format your DateTime:
DateTime yourDateTime = ...//your DateTime value
yourDateTime.ToString("dd/MM/yyyy HH:mm:ss")//or any other format
You can parse user input like this:
DateTime enteredDate = DateTime.Parse(enteredString);
If you have a specific format for the string, you should use the other method:
DateTime loadedDate = DateTime.ParseExact(loadedString, "d", null);
"d" stands for the short date pattern (see MSDN for more info) and null specifies that the current culture should be used for parsing the string.
Remove the last 2 zeros and try.
Your code is
2019-12-04T04:26:29:00
The suggested code change is
2019-12-04T04:26:29

System.FormatException in mscorlib.dll for DateTime conversion

I'm trying to convert an Active Directory attribute (whenCreated) into DateTime then String, but I keep getting a FormatException, any ideas why? Here is the code:
string format = "YYYYMMDDHHMMSS.0Z";
DateTime dt = DateTime.ParseExact(sResult.Properties["whenCreated"][0].ToString(),format,CultureInfo.InvariantCulture);
string whenCreated = dt.ToString();
Also, sResult.Properties["whenCreated"][0].ToString() is the result from an Active Directory search (the date retrieved) and has the String (Generalized Time) syntax.
The DateTime.ParseExact method expects a format string, that tells it where in the input string is which component of a valid date. Your format of 'd' does not meet this criteria. I don't know the content of your input (would help if you add it). But lets assume it would be "2017/31/05 10:27:45" for today. Your format string would then have to be: "yyyy/dd/MM HH:mm:ss"
DateTime dt = DateTime.ParseExact("2017/31/05 10:27:45","yyyy/dd/MM HH:mm:ss",CultureInfo.InvariantCulture);
According to the documentation linked by the OP:
The format for the Generalized-Time syntax is "YYYYMMDDHHMMSS.0Z". An example of an acceptable value is "20010928060000.0Z"
And:
If the time is specified in a time zone other than GMT, the differential between the time zone and GMT is appended to the string instead of "Z" in the form "YYYYMMDDHHMMSS.0[+/-]HHMM". An example of an acceptable value is "20010928060000.0+0200"
So you'd need two format strings in order to parse the strings, like this:
string adDate = "20010928060000.0Z";
string adDate2 = "20010928060000.0+0200";
string format = "yyyyMMddhhmmss.0Z";
string format2 = "yyyyMMddhhmmss.0zzz";
DateTime dtdtdt = DateTime.ParseExact(adDate2, new string[] { format, format2 },
CultureInfo.InvariantCulture,DateTimeStyles.None);

How to convert "2003-11-05T16:35:30Z" to "11/5/2013 " in c#?

I am having a problem while converting
2003-11-05T16:35:30Z to "11/5/2013"
I tried below
DateTime.ParseExact("2003-11-05T16:35:30Z", "dd/MM/yyyy", null)
but I am not getting the value I expect.
You want to do this:
DateTimeOffset.Parse("2003-11-05T16:35:30Z").ToString("dd/MM/yyyy")
What you're doing is parsing the data as if it were in the format dd/MM/yyyy - instead, you want to parse it as the universal format it is, and then convert it to a string with your format string.
DateTime.Parse will take a string and return a date time. To get a string back out, you simply use the ToString method.
Try This:
string myDate = DateTime.ParseExact("2003-11-05T16:35:30Z",
"yyyy-MM-ddTHH:mm:ssZ",null).ToString("M/d/yyyy");
When parsing you specify the format that you are parsing from, then you format the DateTime value using the new format:
string reformatted =
DateTime.ParseExact("2003-11-05T16:35:30Z", "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", null)
.ToString("dd/MM/yyyy");

Parse a string containing date and time in a custom format

I have a string of the next format "ORDER20100322194007", where 20100322 is a date and 194007 is a time. How to parse a string and get the contained DateTime object?
Will it always start with ORDER?
string pattern = "'ORDER'yyyyMMddHHmmss";
DateTime dt;
if (DateTime.TryParseExact(text, pattern, CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt))
{
// dt is the parsed value
}
else
{
// Invalid string
}
If the string being invalid should throw an exception, then use DateTime.ParseExact instead of DateTime.TryParseExact
If it doesn't always begin with "ORDER" then do whatever you need to in order to get just the date and time part, and remove "'ORDER'" from the format pattern above.
You can use DateTime.ParseExact method to specify the format that should be used while parsing.
If you don't have a fixed structure of your string say order will not always be there then you can use regex to separate the numbers and characters and then use convert to datetime function for the numbers separated.

Categories