String was not recognized as a valid DateTime during insert - c#

I get the following error when i try to convert to date time.
String was not recognized as a valid DateTime.
cost.b_date = DateTime.Parse(c_date.Text) ;//c_date.Text = 12/28/2012
Then i try
string date = string.Format("{0:yyyy-MM-dd}",c_date.Text);
cost.b_date = DateTime.Parse(date) ;
but i get the same exception how to fix this problem.

Using string.Format when the input is a string is pointless.
If you know the format of the string, you should use DateTime.ParseExact or DateTime.TryParseExact. For example, for the string you've got, you could use:
DateTime date = DateTime.ParseExact(text, "MM/dd/yyyy",
CultureInfo.InvariantCulture);
You should consider:
Is this user input? If so, use TryParseExact to detect user error more easily without an exception.
Do you definitely know the exact format? If not, using DateTime.TryParse may be more appropriate.
Do you definitely know the culture? If it's not the culture of the current thread, you should specify it explicitly.
Do you have to get the value as text to start with? If you could use an alternative form of input which gives you the value as a DateTime to start with, that would be preferable.

CultureInfo provider = CultureInfo.InvariantCulture;
DateTime result = DateTime.ParseExact(c_date.Text, "d", provider);

Try using DateTime.ParseExact.
DateTime date = DateTime.ParseExact(c_date.Text, "yyyy/MM/dd", null);

Related

converting a string to a DateTime format

I'm trying to parse 09/01/2015 00:00:00 to the format yyyy-MM-ddThh:mm:ssZ using following method:
DateTime.ParseExact("09/01/2015 00:00:00", "yyyy-MM-ddThh:mm:ssZ", (IFormatProvider)CultureInfo.InvariantCulture);
But I'm getting String was not recognized as a valid DateTime
Can anyone tell me why? I believe 09/01/2015 00:00:00 is a valid DateTime format?
From DateTime.ParseExact
Converts the specified string representation of a date and time to its
DateTime equivalent. The format of the string representation must
match a specified format exactly or an exception is thrown.
In your case, they are not.
I assume your 09 part is day numbers, you can use dd/MM/yyyy HH:mm:ss format instead.
var dt = DateTime.ParseExact("09/01/2015 00:00:00",
"dd/MM/yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
Since CultureInfo already implements IFormatProvider, you don't need to explicitly cast it.
I don't understand this. So it means I first have to correct my string
and secondly I can do a ParseExact(). I thought ParseExact could
handle the given string...
ParseExact is not a magical method that can parse any formatted string you suplied. It can handle only if your string and format perfectly matches based on culture settings you used.
Try this code:
var text = "09/01/2015 00:00:00";
var format = "dd/MM/yyyy HH:mm:ss";
var dt = DateTime.ParseExact(text, format, (IFormatProvider)CultureInfo.InvariantCulture);
You'll notice that the format must structurally match the text you're trying to parse exactly - hence the ParseExact name for the method.
The format does not match, you need to change 09/01/2015 into 2015-01-09 or theyyyy-MM-dd part into dd/MM/yyyy.
The ParseExact-method is no ultimate method that converts ANY dateformat into another one, it is simply to parse a given string into a datetime using the provided format. Thus if your inout does not match this format the method will throw that exception.
As a datetime is internally only a number there is no need to convert one format into another at all, so as long as you know your input-format you can build a date from it which has nothing to do with any formatting which you may need when you want to print that date to your output. In this case you WILL need a formatter.
As most people have stated the error is coming from the fact that the date in string format doesn't match the format you are saying it's in. You are saying that 09/01/2015 00:00:00 is in the format "yyyy-MM-ddThh:mm:ssZ", which it's not, hence the error. To rectify this you need to either alter the format the string is in, or more likely, change the format you are saying the date is in. So change "yyyy-MM-ddThh:mm:ssZ" to "dd/MM/yyyy HH:mm:ss".
In a more long term view how are you arriving at that date? Is it possible that the format may change (input but the user)? If so it might be better to try and avoid the error being thrown and handle it better with TryParseExact. To make use of this best I generally output a nullable DateTime and then check if it's null. If you don't do this then if the parse fails it will simply make the output datetime the minimum value.
Something like this should work:
public DateTime? StringToDate (string dateString, string dateFormat)
{
DateTime? dt;
DateTime.TryParseExact(dateString, dateFormat, null, System.Globalization.DateTimeStyles.None, out dt);
return dt;
}
Then you can use it like this:
DateTime? MyDateTime = StringToDate("09/01/2015 00:00:00", "dd/MM/yyyy HH:mm:ss");
if(MyDateTime != null)
{
//do something
}
Another simple way to do this...
var dt = Convert.ToDateTime(Convert.ToDateTime("09/01/2015 00:00:00").ToString("yyyy-MM-ddThh:mm:ssZ"))

Convert date time to string and back to date time

I'm having a troubles with converting strings to DateTime. Here is what I have. First I convert current date to string (this will be folder name).
string dateString = string.Format("{0:yyyy-MM-dd_HH-mm-ss}", DateTime.Now);
Output like this
2013-05-16_09-32-47
Then I create a folder. During program execution I get this folder and I need to convert it's name back to DateTime. Try to make it like this
DateTime directoreDate = DateTime.ParseExact(directory.Name, "0:yyyy-MM-dd_HH-mm-ss", CultureInfo.InvariantCulture);
But it throws FormatException. Can anybody tell me why this happening.
You are using the same composite format string that you used to format the original DateTime. This is not needed for ParseExact - drop the 0: from it:
DateTime directoreDate = DateTime.ParseExact(directory.Name,
"yyyy-MM-dd_HH-mm-ss",
CultureInfo.InvariantCulture);
Use
DateTime directoreDate = DateTime.ParseExact(directory.Name, "yyyy-MM-dd_HH-mm-ss", CultureInfo.InvariantCulture);
Remove 0: from DateTime.ParseExact, It was used as a place holder in string.Format().
Use as :
DateTime directoreDate = DateTime.ParseExact(directory.Name,
"yyyy-MM-dd_HH-mm-ss",
CultureInfo.InvariantCulture);

C# Datetime format conversion

I have a conversion problem with datetime. I have a date string as MM/dd/yyyy. Now I need to convert it to yyyy-MM-dd.
But I'm facing some error. Please help
public static DateTime ToDBDateTime(string _dateTime)
{
string sysFormat = "MM/dd/yyyy hh:mm:ss tt";
string _convertedDate = string.Empty;
if (_dateTime != null || _dateTime != string.Empty)
{
_convertedDate = DateTime.ParseExact(_dateTime, sysFormat, System.Globalization.CultureInfo.InvariantCulture).ToString(_toDBDateFormat);
//_convertedDate = Convert.ToDateTime(_dateTime).ToString(_toDBDateFormat);
/// Debug.Print(sysFormat);
}
return Convert.ToDateTime(_convertedDate);
}
And I want to know that is there is any way to pass the datetime in various formats and it would return the expected format.
E.g.: if I pass date as dd/MM/yyyy or MM/dd/yyyy, the above function would return the date in format as yyyy-MM-dd.
Please provide some suggestion to solve datetime issues.
I have a date string as MM/dd/yyyy
Right... and yet you're trying to parse it like this:
string sysFormat = "MM/dd/yyyy hh:mm:ss tt";
...
_convertedDate = DateTime.ParseExact(_dateTime, sysFormat,
CultureInfo.InvariantCulture)
You need to give a format string which matches your input - so why are you including a time part? You probably just want:
string sysFormat = "MM/dd/yyyy";
However, that's not the end of the problems. You're then converting that DateTime back into a string like this:
.ToString(_toDBDateFormat)
... and parsing it once more:
return Convert.ToDateTime(_convertedDate);
Why on earth would you want to do that? You should avoid string conversions as far as possible. Aside from anything else, what's to say that _toDBDateFormat (a variable name which raises my suspicions to start with) and Convert.ToDateTime (which always uses the current culture for parsing) are going to be compatible?
You should:
Work out how you want to handle being given an empty string or null, and just return an appropriate DateTime then
Otherwise, just parse using the right format.
This part of your question also concerns me:
E.g.: if I pass date as dd/MM/yyyy or MM/dd/yyyy, the above function would return the date in format as yyyy-MM-dd.
There's no such thing as "the date in format as yyyy-MM-dd". A DateTime is just a date and time value. It has no intrinsic format. You specify how you want to format it when you format it. However, if you're using the value for a database query, you shouldn't be converting it into a string again anyway - you should be using parameterized SQL, and just providing it as a DateTime.
As you have a date in a string with the format "MM/dd/yyyy" and want to convert it to "yyyy-MM-dd" you could do like this:
DateTime dt = DateTime.ParseExact(dateString, "MM/dd/yyyy", CultureInfo.InvariantCulture);
dt.ToString("yyyy-MM-dd");
Use the inbuilt tostring like this:
Convert.ToDateTime(_convertedDate).ToString("MM/dd/yyyy") or whatever format you want.
I tried this and its working fine.
DateTime date1 = new DateTime(2009, 8, 1);
date1.ToString("yyyy-MM-dd hh:mm:ss tt");
You can apply any format in this ToString.
Hope that helps
Milind

Convert YYYYMMDD string to MM/DD/YYYY string

I have a date that is stored as a string in the format YYYYDDMM. I would like to display that value in a 'MM/DD/YYYY' format. I am programming in c#. The current code that I am using is as follows:
txtOC31.Text = dr["OC31"].ToString().Trim();
strOC31date = dr["OC31DATE"].ToString().Trim();
DateTime date31 = DateTime.Parse(strOC31date);
strOC31date = String.Format("{0:MM/dd/yyyy}", date31);
However, I am getting an error because the YYYYMMDD string (strOC31date) is not being recognized as a valid datetime.
DateTime.ParseExact with an example
string res = "20120708";
DateTime d = DateTime.ParseExact(res, "yyyyddMM", CultureInfo.InvariantCulture);
Console.WriteLine(d.ToString("MM/dd/yyyy"));
Use ParseExact() (MSDN) when the string you are trying to parse is not in one of the standard formats. This will allow you to parse a custom format and will be slightly more efficient (I compare them in a blog post here).
DateTime date31 = DateTime.ParseExact(strOC31date, "yyyyMMdd", null);
Passing null for the format provider will default to DateTimeFormatInfo.CurrentInfo and is safe, but you probably want the invariant culture instead:
DateTime date31 = DateTime.ParseExact(strOC31date, "yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
Then your code will work.
Instead of DateTime.Parse(strOC31date); use DateTime.ParseExact() method, which takes format as one of the parameters.
You want the method DateTime.ParseExact.
DateTime date31 = DateTime.ParseExact(strOC31date, "yyyyddMM", CultureInfo.InvariantCulture);

DateTime FormatException error

DateTime datuMDokumenta = Convert.ToDateTime(txtDatumDokum.Text);
txtDatumDokum.Text is like "09.09.2011".
but i get FormatException error. Must i parse date?
Try DateTime.ParseExact with the dd.MM.yyyy format string
DateTime.ParseExact(txtDatumDokum.Text, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None);
It's not good to see, anyway try this:
string s = "09.09.2011";
DateTime dt = Convert.ToDateTime(
s.Replace(".",
new System.Globalization.DateTimeFormatInfo().DateSeparator));
You need to tell us why the text input is using this format. If it is because the user enters it this way, then you need to make sure that the format matches that given by Thread.CurrentCulture.DateTimeFormat.ShortDatePattern. Changing the culture (by setting
Thread.CurrentCulture) to an appropriate value will then solve your problem.
If you are supposed to parse the input no matter what format it is in, then you will need to do some manual processing first (perhaps remove spaces and other delimiter characters from the input with string.Replace) and then try to parse the date using DateTime.ParseExact and a known format string.
But it all depends on why the input has that format, and why your application's current culture does not match it.
You could try this, TryParse avoids parsing exceptions.. Then you just need check result to be sure that it parsed.
DateTime datuMDokumenta;
bool result = DateTime.TryParse(txtDatumDokum.Text, out datuMDokumenta);
You will have to determine if this is a good solution for your application.
See this example:
http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx
Judging by the date you gave you need to include a culture, de-DE accepts 01.01.11 type of dates but I'm not sure which one you actually want to use, you'll need to decide that.. the Code would look like this:
using System.Globalization;
DateTime datuMDokumenta;
bool result = DateTime.TryParse(txtDatumDokum.Text, CultureInfo.CreateSpecificCulture("de-DE"), DateTimeStyles.None, out datuMDokumenta);
A list of cultures can be found here, select the appropriate one for you:
http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo%28v=vs.71%29.aspx
The plus here is that this code is a bit more work but it is very difficult to break. Assuming you are using a free text entry on a TextBox you don't want to be throwing exceptions.
Yes you have to parse input date in current culture.
string[] format = new string[] { "dd.MM.yyyy" };
string value = "09.09.2011";
DateTime datetime;
if (DateTime.TryParseExact(value, format, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.NoCurrentDateDefault, out datetime))
//Valid
else
//Invalid
DateTime dt = Convert.ToDateTime(txtDatumDokum.Text)
It is right...there is no isssue
During a Deserialization call under compact framework 3.5 i've had some unexpected behaviour before.
I've converted from using the OpenNETCF serialization classes to the framework XML serialization class. In doing so, the default time format has changed and the order of property/public members. So long story short, i've exposed a text property which converts my date-times back to the format my VB6 application is expecting.
Dim dumbDate As New Date
Dim formats() As String = {"yyyy-MM-ddTHH:mm:ss.fffzzz", _
"yyyy-MM-dd HH:mm:ss:fffffffzzz"}
_datetimeTaken = dumbDate.ParseExact(value, formats, CultureInfo.InvariantCulture, DateTimeStyles.None)
' There is something wrong with compact framework during the Serialization calls.
' calling the shared method Date.Parse or Date.ParseExact does not produce the same
' result as calling a share method on an instance of Date. WTF?!?!?!
' The below will cause a "Format" exception.
'_datetimeTaken = Date.ParseExact(value, formats, CultureInfo.InvariantCulture, DateTimeStyles.None)
Date.blah doesn't work. dumbDate.blah works. strange.
public static void Main(string[] args)
{
var dt = new DateTime(2018, 04, 1);
Console.WriteLine(dt);
string month = dt.ToString("MMMM");
Console.WriteLine(month); //April
month = dt.ToString("MMM");
Console.WriteLine(month); //Apr
month = dt.ToString("MM");
Console.WriteLine(month); //04
Console.ReadKey();
}
your code:
DateTime datuMDokumenta = Convert.ToDateTime(txtDatumDokum.Text);
try changing this to:
DateTime datuMDokumenta = Convert.ToDateTime(txtDatumDokum);
and when u print the date/time
print datuMDokumenta.Text

Categories