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

Worked with phpMyAdmin, and wanted to update data from C#.
I had "yyyy-MM-dd" format for column dateBuy in phpMyAdmin.
To display it, I changed the format to "dd/MM/yyyy" in C#.
This is the code: (I don't have problem with this code)
string dateBuy = dr.GetValue(1).ToString();
DateTime time = DateTime.Parse(dateBuy);
dateBuy = time.ToString("dd/MM/yyyy");
To update database, I wanted to change the format back to "yyyy-MM-dd". But, I had an error: "String was not recognized as a valid DateTime".
This is the error parts of my code:
string dateBuy2 = txtDateBuy.Text;
dateBuy = (DateTime.ParseExact(dateBuy2, "yyyy-MM-dd", null)).ToString();
Did I make mistake in the DateTime syntax? Thanks for your help.

[Since it is not good if we continue in the comments (the comments will be long), I will just put up what I think as a solution here]
To format dateBuy to the format that you want, you should also put the string format in the ToString()
That is, instead of
dateBuy = (DateTime.ParseExact(dateBuy2, "yyyy-MM-dd", null)).ToString();
put
dateBuy = (DateTime.ParseExact(dateBuy2, "yyyy-MM-dd", null)).ToString("yyyy-MM-dd");
Otherwise, it is possible for the ToString() to produce something like "2015-10-16 12:00:00 AM" instead of "2015-10-16"
However, since you use ParseExact, the input for the dateBuy2 must also be in the format of "yyyy-MM-dd" which defeats the purpose. You may consider using DateTimePicker such that you can control the input format.
Alternatively, you can use DateTime.Parse or TryParse (as suggested by Martheen) instead, something like this
try {
DateTime dt = DateTime.Parse(txtDateBuy.Text);
dateBuy = dt.ToString("yyyy-MM-dd");
} catch (Exception exc) {
//wrong format, do something to tell the user
}
If input has to be in the TextBox you better put try-catch to prevent your program crash for taking wrong-formatted input if you use Parse.
Where as if you use TryParseyou can put it in if-else block statement instead
DateTime dt;
if (DateTime.TryParse(txtDateBuy.Text, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out dt)) {
//correct format, do something using dt
} else {
//incorrect format, warns the user
}
To get CultureInfo enum you need to add reference to System.Globalization
[Edited after suggestion given by Mr. Soner Gonul]

Related

how to compare datetime value from database with textbox datetime value

I want to compare database datetime value that is stored in dd/mm/yyyy format, with the textbox value that is stored in dd-mmm-yyyy format.
I have tired converting the database value to dd-mmm-yyyy format using parseexact-
DateTime dtdb = DateTime.ParseExact(dr["paydate"].ToString(), "dd-MMM-yyyy",null);
and then comparing with the textbox value,
if(dtdb.ToString() != txtpaydate.Text)
But its giving me this error:
String was not recognized as a valid DateTime.
I also tried doing this:
Convert.ToDateTime(dr["paydate"]).ToString("dd-MMM-yyyy")!= txtpaydate.text
but its still giving me the same error. Please let me know how can I solve this issue. Thank you.
you can convert DateTime value and textbox DateTime value to timestamp (from 1970-0-0) then compare it
edited
maybe you want to read rfc3389 about timestamp
You need to parse your textbox into DateTime object and than you can completely free to use general arithmetic operations such as:
if (dtdb > dttb) and etc. If you have any trouble for parsing it, check this page for further information.
If there's any more question, feel free to ask here. But please check stackoverflow before. Have a great day.
string dtdb =dr["paydate"].ToString("dd-MMM-yyyy");
var dt=txtpaydate.Text.ToString("dd-MMM-yyyy");
if(dtdb!= dt)
{
//do what you want
}
As said, it's best to manipulate pure DateTime objects.
You can do it this way:
// Example strings
var myDate1AsString = "31/12/2016";
var myDate2AsString = "31-dec-2016";
// DateTime object used to retrieved the dates as string
var myDate1AsDate = new DateTime();
var myDate2AsDate = new DateTime();
// Parse the strings; if the parse fail, the date is set to DateTime.MinValue
DateTime.TryParseExact(myDate1AsString, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out myDate1AsDate);
DateTime.TryParseExact(myDate2AsString, "dd-MMM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out myDate2AsDate);
// Correctly compare the dates
var result = DateTime.Compare(myDate1AsDate, myDate2AsDate);
// or, directly compare a date with the other.
if (!myDate1AsDate.Equals(myDate2AsDate))
{
// Do some stuff.
}
Always use a CultureInfo when parsing date.

Converting datetime format without using SAP RFC with C#

I got a problem when trying to convert a date-time format with SAP RFC.
I'm trying this:
string tmpDate = argDate.ToString("dd.MM.yyyy");
DateTime date = Convert.ToDateTime(tmpDate);
IRfcFunction SAPRateAPI = null;
SAPRateAPI = _ecc.Repository.CreateFunction("ZRFC_CUST_CONDITION_RATE");
SAPRateAPI = CreateSAPRateAPI(SAPRateAPI, argPartnerSAPTranCode, argCustSAPTranCode, argMaterialCode, date);
SAPRateAPI.Invoke(_ecc);
But getting an error 'Specified Cast is not valid'
DateTime in C# has its own representation and doesn't has any "format" which you can see or change.
So phrase "datetime in dd.mm.yyyy format" has no sense at all.
Let's look at your code:
string tmpDate = argDate.ToString("dd.MM.yyyy");
DateTime date = Convert.ToDateTime(tmpDate);
Here you're converting DateTime to string and then back to DateTime.
You're getting exception on back cast just because Convert uses your windows specified culture, and in the case it differs from the one in the string - you need DateTime.ParseExact and explicit format specification.
But even if this cast will be successful - you again will get DateTime and this two lines will not change its format.
It looks like all you need - is just pass date only part of datetime as argument of your function. But it can be achieved pretty easily without any casts just by using argDate.Date (assuming agrDate is DateTime)
DateTime date = new DateTime( argDate.Years, argDate.Month, argDate.Day );
I think this is what you want.
See: C# Reference
Edit:
Which is the same as Andy Korneyev solution - Ok, his is nicer too look at, but both create a second DateTime object.
Consider using the DateTime.ParseExact method.
// Parse date and time with custom specifier.
string format = "dd.mm.yyyy hh:mm:tt";
DateTime date;
try {
date = DateTime.ParseExact(argDate, format, CultureInfo.InvariantCulture);
}
catch (FormatException e) {
throw new ArgumentException("argDate", e);
}

converting date string to date format

I have tried out as many suggestions as I've found on Stackoverflow, but not getting the desired result. Any help would be much appreciated.
My date string is "04-Dec-2013 14:14:02.143" and I want to convert this exactly as into DateTime format.
This was the last suggestion I tried:
String MyString;
MyString = "04-Dec-2013 14:14:02.143";
DateTime MyDateTime;
MyDateTime = new DateTime();
MyDateTime = DateTime.ParseExact(MyString, "dd-MMM-yyyy HH:mm:ss.fff",
null);
However, I keep getting the undesired result of "04/12/2013 14:14:02" rather want it to be "04-Dec-2013 14:14:02.143".
Any suggestions?
Yes, you should read about DateTime struct. It has not have any format info attached, it's just a plain number representing point in time.
The format come into play when you try to get string representation of the data, using ToString(format) method.
Use the format string every time you're calling ToString to get the date in the format you want it to be:
var stringDateRespresentation = dateValue.ToString("dd-MMM-yyyy HH:mm:ss.fff");
To make things easier you should pass plain, non-formatted DateTime instances all around and change it into string using ToString method only when it's being presented to the user.
#MarcinJuraszek has better answer on this question, but it does not solve the problem of different datetime patterns, because of what great SO users mark other questions as duplicate.
string MyString = "Dec-12-2013 14:14:02.143";
CultureInfo ukCulture = new CultureInfo("en-GB");
ukCulture.DateTimeFormat.ShortDatePattern = "MMM-dd-yyyy HH:mm:ss.fff";
DateTime myDateTime = DateTime.Parse(MyString, ukCulture.DateTimeFormat);
string QbDate = myDateTime.ToString("dd-MMM-yyyy HH:mm:ss.fff");
To solve the issue of different date-time patterns override any date pattern of any culture
As mentioned by #MarcinJuraszek the format comes into picture when you convert it back to string. The format you mentioned in ParseExact is for the parsing. i.e. How will MyString be parsed to create a DateTime object.
See below example just so you understand how the ParseExact format string is used.
If you use MyDateTime.ToString("dd-MMM-yyyy HH:ss:mm.fff"); instead (see I swapped mm and ss) in ParseExact you will get "12/4/2013 2:02:14 PM" instead of "12/4/2013 2:14:02 PM"

Convert dd/MM/yyyy to yyyy/MM/dd?

I want to convert a string '30/12/2012' to '2012/12/30'. My application is set to "en-CA" however the database accepts yyyy/MM/dd as default.
How can I do this without depending on the current culture info set
at server?
As all the comments have said, but none of the answers have said so far: don't pass this to the database as a string.
Parse any text you receive as early as possible, then use DateTime to represent it everywhere else, including how you send it to the database, via parameterized SQL1. This goes for values of all kinds: convert it into the "natural" type for the data as soon as possible, and keep it in that natural representation for as long as possible. A date isn't a string, and you should only convert it to a string if you really, really need to - ideally just before displaying it to a user.
The parsing can be done with DateTime.ParseExact or DateTime.TryParseExact depending on whether this is "suspicious" data (e.g. from a user) or data which should really be correct and for which an exception is the most appropriate reaction to unparseable values. I suggest you pass in CultureInfo.InvariantCulture with your custom format string. For example:
DateTime date = DateTime.ParseExact(text, "dd/MM/yyyy",
CultureInfo.InvariantCulture);
(If you do a lot of date/time work, you may also want to consider using my Noda Time project which allows you to express the value in a richer way - in this case you'd probably use LocalDate.)
1 If you're not already using parameterized SQL, but are instead baking values directly into the SQL, you have bigger problems than date/time conversions.
You can specify CultureInfo in Format and most ToString functions.
I.e. DateTime.ToString(CultureInfo) and DateTime.Parse(string, CultureInfo) will let you pars string in one culture (i.e. current or new CultureInfo("en-CA")) and format with another like new CultureInfo("en-us").
Note: you may consider running all DB access under some other culture (i.e. en-US) by setting Thread.CurrentCulture as sometimes number fomats are also impacted (if numbers are storead as string).
If its going to always be in the same format. Then split it on the / character
string[] tempsplit = datestring.Split('/');
and then put it back together
string joinstring = "/";
string newdate = tempsplit[2] + joinstring + tempsplit[1] + joinstring + tempsplit[0];
simple.
First convert your string to DateTime format using
DateTime dt = Convert.ToDateTime("your string value");
Then save it in string using:
string st=dt.ToString("yyyy/MM/dd");
This will convert your date format to any desired format you want without depending on culture
Without going into the issue what format the database accepts or not, you can do the conversion like this:
Convert the String to Datetime like explained here
Change the format and convert it to string again like this
This seems to work.
var x = new string[] { "2012/06/12", "20/06/2012", "111/111/1111" };
foreach (var ds in x)
{
DateTime d = default(DateTime);
try
{
d = DateTime.Parse(ds, CultureInfo.GetCultureInfo("en-CA"));
}
catch (Exception ex)
{
try
{
d = DateTime.ParseExact(ds, "yyyy/MM/dd", CultureInfo.InvariantCulture);
}
catch
{
}
}
if (d == default(DateTime))
Console.WriteLine("error");
else
Console.WriteLine(d.ToString());
}

String was not recognized as a valid DateTime " format dd/MM/yyyy"

I am trying to convert my string formatted value to date type with format dd/MM/yyyy.
this.Text="22/11/2009";
DateTime date = DateTime.Parse(this.Text);
What is the problem ?
It has a second override which asks for IFormatProvider. What is this? Do I need to pass this also? If Yes how to use it for this case?
Edit
What are the differences between Parse and ParseExact?
Edit 2
Both answers of Slaks and Sam are working for me, currently user is giving the input but this will be assured by me that they are valid by using maskTextbox.
Which answer is better considering all aspects like type saftey, performance or something you feel like
Use DateTime.ParseExact.
this.Text="22/11/2009";
DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", null);
You need to call ParseExact, which parses a date that exactly matches a format that you supply.
For example:
DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
The IFormatProvider parameter specifies the culture to use to parse the date.
Unless your string comes from the user, you should pass CultureInfo.InvariantCulture.
If the string does come from the user, you should pass CultureInfo.CurrentCulture, which will use the settings that the user specified in Regional Options in Control Panel.
Parsing a string representation of a DateTime is a tricky thing because different cultures have different date formats. .Net is aware of these date formats and pulls them from your current culture (System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat) when you call DateTime.Parse(this.Text);
For example, the string "22/11/2009" does not match the ShortDatePattern for the United States (en-US) but it does match for France (fr-FR).
Now, you can either call DateTime.ParseExact and pass in the exact format string that you're expecting, or you can pass in an appropriate culture to DateTime.Parse to parse the date.
For example, this will parse your date correctly:
DateTime.Parse( "22/11/2009", CultureInfo.CreateSpecificCulture("fr-FR") );
Of course, you shouldn't just randomly pick France, but something appropriate to your needs.
What you need to figure out is what System.Threading.Thread.CurrentThread.CurrentCulture is set to, and if/why it differs from what you expect.
Although the above solutions are effective, you can also modify the webconfig file with the following...
<configuration>
<system.web>
<globalization culture="en-GB"/>
</system.web>
</configuration>
Ref : Datetime format different on local machine compared to production machine
You might need to specify the culture for that specific date format as in:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB"); //dd/MM/yyyy
this.Text="22/11/2009";
DateTime date = DateTime.Parse(this.Text);
For more details go here:
http://msdn.microsoft.com/en-us/library/5hh873ya.aspx
Based on this reference, the next approach worked for me:
// e.g. format = "dd/MM/yyyy", dateString = "10/07/2017"
var formatInfo = new DateTimeFormatInfo()
{
ShortDatePattern = format
};
date = Convert.ToDateTime(dateString, formatInfo);
After spending lot of time I have solved the problem
string strDate = PreocessDate(data);
string[] dateString = strDate.Split('/');
DateTime enter_date = Convert.ToDateTime(dateString[1]+"/"+dateString[0]+"/"+dateString[2]);
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;
}
use this to convert string to datetime:
Datetime DT = DateTime.ParseExact(STRDATE,"dd/MM/yyyy",System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat)
Just like someone above said you can send it as a string parameter but it must have this format: '20130121' for example and you can convert it to that format taking it directly from the control. So you'll get it for example from a textbox like:
date = datetextbox.text; // date is going to be something like: "2013-01-21 12:00:00am"
to convert it to: '20130121' you use:
date = date.Substring(6, 4) + date.Substring(3, 2) + date.Substring(0, 2);
so that SQL can convert it and put it into your database.
Worked for me below code:
DateTime date = DateTime.Parse(this.Text, CultureInfo.CreateSpecificCulture("fr-FR"));
Namespace
using System.Globalization;
You can use also
this.Text = "22112009";
DateTime newDateTime = new DateTime(Convert.ToInt32(this.Text.Substring(4, 4)), // Year
Convert.ToInt32(this.Text.Substring(2,2)), // Month
Convert.ToInt32(this.Text.Substring(0,2)));// Day
Also I noticed sometimes if your string has empty space in front or end or any other junk char attached in DateTime value then also we get this error message

Categories

Resources