Error on DateTime.ParseExact - c#

I have a date in an oracle database, that I query on. This date looks like:
5/3/2016 (after I remove the time portion)
I try to convert this date to a DateTime. I am using:
ParseExact(String, String, IFormatProvider)
I am doing something wrong, which I can't figure out.
My code is shown below. Notice that the variable called "res", has the value 5/3/2016 as described above
try {
while(reader.Read()) {
string res = reader[0].ToString().Substring(0, 8);
mailer.SendSmtpMail4dev("Result: " + res);
mailer.SendSmtpMail4dev("Result: " + DateTime.ParseExact(res, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture));
}
} catch(Exception e) { ...

for DateTime.ParseExact The format of the input string and the format string should be the same, so use:
DateTime.ParseExact(res, "d/M/yyyy", System.Globalization.CultureInfo.InvariantCulture);
In your case the supplied date is 5/3/2016 and you are specifying that the format is "dd-MM-yyyy" such conversions are not possible. if you need to change the format means you can do like the following:
string res = "5/2/2016";
DateTime givenDate = DateTime.ParseExact(res, "d/M/yyyy", System.Globalization.CultureInfo.InvariantCulture);
string newFormatedDate = givenDate.ToString("dd-MM-yyyy");

Use:
DateTime.ParseExact(res, "d/M/yyyy", System.Globalization.CultureInfo.InvariantCulture);
Refer to the MSDN article for details

Use
DateTime.ParseExact(res, "d/M/yyyy", System.Globalization.CultureInfo.InvariantCulture).ToString("dd-MM-yyyy")

since your res date is dd/MM/yyyy format but you have tried to cast is as dd-MM-yyyy, in DateTime.ParseExact() you have to provide datetime and format string as same format, correct code will be like this
mailer.SendSmtpMail4dev("Result: " + DateTime.ParseExact(res, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture).ToString("dd-MM-yyyy"));

If you have a date why do you convert it to String
// What if server's NLS_* settings are changed? What does 8 stand for?
reader[0].ToString().Substring(0, 8);
and then Parse again? If reader[0] is a date use DateTime:
try {
while(reader.Read()) {
// 0th field is date, then treat it as being date
DateTime date = Convert.ToDateTime(reader[0]);
//TODO: put the right formats here
mailer.SendSmtpMail4dev("Result: " + date.ToString("dd-MM-yyyy"));
mailer.SendSmtpMail4dev("Result: " + date.ToString("dd-MM-yyyy"));
}
}
catch(Exception e) {
...
}

The solution to my problem is marked above, but I just want to state something important, so that others might save some time. Some suggested solutions, suggest doing: DateTime.ParseExact(res, "dd/MM/yyyy" ...) which also seems to be in many other examples on the net, so I'm not saying it's wrong. However. This didn't work for me, I spent some time, before I tried doing:
DateTime.ParseExact(res, "d/M/yyyy" ...)
Notice that in the later solution, there is only one d, and one M.
But my main problem, like everyone pointed out, was probably that I was using:
"dd-MM-yyyy" instead of "dd/MM/yyyy" (which is the same format as the oracle value)
Hope this will save you some time

Related

CONVERT date format from mm-dd-yyyy to dd-mmm-yyyy in c#

I am trying insert asp.net form field values to oracle database table. I have a date field which is in "MM-DD-YYYY" format. I need to add that date to oracle table. So i am trying to convert that date format to "DD-MMM-YYYY" format. But i am getting the following error.
code:
var creation_date = DateTime.ParseExact(CreationDateTextBox.Text, "DD-MMM-YYYY",null);
Text box value is: 12-12-2013.(No time)
i am getting error like "String was not recognized as a valid DateTime".
You need to parse the date using MM-dd-yyyy but then you shouldn't need to format it at all. Just pass it to the database as a DateTime using parameterized SQL.
DateTime creationDate;
if (DateTime.TryParseExact(CreationDateTextBox.Text, "MM-dd-yyyy",
CultureInfo.InvariantCulture, DateTimeStyles.None,
out creationDate))
{
// Use creationDate within a database command, but *don't* convert it
// back to a string.
}
else
{
// Handle invalid input
}
Avoid string conversions wherever you can. Indeed, ideally use a date/time picker of some description rather than just a text field - that will give users a better experience and reduce the risk of poor conversions.
Also note that whenever you want to use custom string conversions (parsing or formatting) you should read the MSDN docs - YYYY and DD aren't valid format specifiers.
This might help :)
String myString = "12-30-2014"; // get value from text field
DateTime myDateTime = new DateTime();
myDateTime = DateTime.ParseExact(myString, "MM-dd-yyyy",null);
String myString_new = myDateTime.ToString("dd-MM-yyyy"); // add myString_new to oracle
Try this
DateTime dt = Convert.ToDateTime(CreationDateTextBox.Text);
var creation_date=String.Format("{0:dd-MMM-yyyy}", dt)
OR try as
dt.ToString("dd MMM yyyy");
You have three M for the month, which is used for month names. Just use two M.
private DateTime ConvertToDateTime(string strDateTime)
{
DateTime dtFinaldate; string sDateTime;
try { dtFinaldate = Convert.ToDateTime(strDateTime); }
catch (Exception e)
{
string[] sDate = strDateTime.Split('/');
sDateTime = sDate[1] + '/' + sDate[0] + '/' + sDate[2];
dtFinaldate = Convert.ToDateTime(sDateTime);
}
return dtFinaldate;
}

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

Datetime conversion in C# - using formats

I need to convert a String to DateTime format, for this I just tried like
DateTime.ParseExact(DateOfBirth,"MM/dd/yyyy",CultureInfo.InvariantCulture);
it's working fine when I pass the value like 05/30/2012.
But if I try to pass the value as 5/30/2012 its showing error:
String was not recognized as a valid DateTime
To fix this I tried like
DateTime.ParseExact(String.Format("{0:MM/dd/yyyy}", DateOfBirth), "MM/dd/yyyy",
CultureInfo.InvariantCulture);
it's still not working. Here If I try String.Format("{0:MM/dd/yyyy}", DateOfBirth) for the value 5/30/2012 its showing the same format instead of 05/30/2012.
How can I fix this, can anyone help me here...
check this link
string to DateTime conversion in C#
Use M/d/yyyy instead of the format specifier you're using. Using only a single M matches months with leading zeros as well. This is also true for d.
assuming your DateOfBirth string is always separated by slashes, you could try something like this:
string[] dateParts = DateOfBirth.Split('/');
DateTime.ParseExact(string.Format("{0:00}", dateParts[0]) + "/" + string.Format("{0:00}", dateParts[1]) + "/" + string.Format("{0:0000}", dateParts[2]));
I think the issue is the format string can't be recognized since DateOfBirth is not a DateTime object. Thus, you enforce formatting by reformatting the string yourself
There is an overload which might be of your interest
DateTime.ParseExact(DateOfBirth,
new[] { "MM/dd/yyyy", "M/dd/yyyy" },
CultureInfo.InvariantCulture,
DateTimeStyles.None);
This should help you take care of single as well as two digit month part (since 5 is failing for you as the format is MM)
Since you have separators in your string (ie /), you can just do;
DateTime.ParseExact(DateOfBirth,"M/d/yyyy",CultureInfo.InvariantCulture);
That will parse either single or double digit days/months. When you use MM/dd/yyyy, you're requiring them both to be double digit numbers, and that's obviously not what you want in this case.
Try just "d" instead of "MM/dd/yyyy".
So, the statement should be:
var date = DateTime.ParseExact(DateOfBirth, "d", CultureInfo.InvariantCulture);
The documentation for this is here:
http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx
Edit
Oops, I misread the documentation. It should be "M/d/yyyy".
In case you need to make it culture-independent..
var dateTimeFormat = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentUICulture.Name).DateTimeFormat;
dateTimeFormat.ShortDatePattern =
Regex.Replace(Regex.Replace(dateTimeFormat.ShortDatePattern, "[M]+", "MM"), "[d]+", "dd");
var newDate = date.HasValue ? date.Value.DateTime.ToString("d", dateTimeFormat) : null;

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