Posted: 6/16/2011
How to convert a string to datetime
My code is
DateTime dt = DateTime.Now;
string date1 = dt.ToString("MM/dd/yyyy HH:mm:ss");
dt =Convert.ToDateTime(date1);
I have got error :-String was not recognized as a valid DateTime.
at line dt =Convert.ToDateTime(date1);
Please help!
Posted: 6/17/2011
Hi Pallavi,
You need to call DateTime.ParseExact which parses a date that exactly matches a format you supply.
For example:
string date1="11/25/2011 12:10:30"; DateTime date2 = DateTime.ParseExact(date1, "MM/dd/yyyy HH:mm:ss", null);
null means "the current culture...", unless your string comes from the user, you should pass CultureInfo.InvariantCulture, for example:
date2 = DateTime.ParseExact(date1, "MM/dd/yyyy HH:mm:ss", 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.
And you should add:
using System.Globalization;
Best Regards,
Gjorgji
Nice reply Gjorgi.
In addition, I would use TryParseExact in order to ensure the code won't break while trying to parse the DateTime.
Also, passing 'null' as a FormatProvider is quite dangerous, so by default I would pass CultureInfo.InvariantCulture.
Here is an example
string date1 = "11.25.2011 12:10:30"; DateTime date2; if (DateTime.TryParseExact(date1, "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out date2)) { Response.Write(date2.ToString("MM/dd/yyyy")); } else { Response.Write("Parsing failed!"); }
Hi Hajan ,
Actually I want to remove AM/Pm from the date
I am using DateTime.Now; which gives me date in format: 17/06/2011 2:53:32 PM
really my issue is I have datetime datatype field in table (Mysql)
When I am inserting datevalue it giving me error i.e Incorrect datetime value: '17/06/2011 2:53:32 PM' for column 'date' at row 1
Mysql stores date in to the format i.e 2011-06-13 11:32:48
Regards,
Pallavi
If you want to format the date exactly as your Mysql format you should use string formater using standard format specifiers. As you mantion you format look like "Universal Sortable Date Time"
Try to format like these:
String.Format("{0:u}", dt); // "2011-06-17 16:05:07Z" UniversalSortableDateTime
or just "Sortable Date Time":
String.Format("{0:s}", dt); // "2011-06-17T16:05:07" SortableDateTime
Or you can specify Invariant DateTimeFormat in the following way:
string date1 = "11/25/2011 12:10:30"; DateTime date2; if (DateTime.TryParseExact(date1, "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out date2)) { DateTimeFormatInfo DateTimeFormat = CultureInfo.InvariantCulture.DateTimeFormat; Response.Write(date2.ToString(DateTimeFormat.SortableDateTimePattern)); } else { Response.Write("Parsing failed!"); }
Or you can specify the exact formatting string in the following way:
string date1 = "11/25/2011 12:10:30"; DateTime date2; if (DateTime.TryParseExact(date1, "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out date2)) { Response.Write(date2.ToString("yyyy-MM-dd hh:mm")); } else { Response.Write("Parsing failed!"); }
Both should work fine with MySQL db.
Hope this helps,Hajan
Posted: 6/20/2011
Hi Gjorgji,Hajan
thank you for both of you for nice reply
but hajan you have given me example where you r storing fix date I want to store DateTime.Now
like this
DateTime dt=DateTime.Now;
string strdt=dt.ToString();
if (DateTime.TryParseExact(strdt, "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt)) { Response.Write(date2.ToString("yyyy-MM-dd hh:mm")); }
but its not matching becoz DateTime.Now gives 11/25/2011 12:10:30 PM
I hop you will get it
please reply it's urgent
hi pallavi,
If you have DateTime and not string, then you don't need to use TryParseExact or ParseExact at all. These methods are intended for parsing strings to datetime.
So, you can try directly with:
DateTime dt = DateTime.Now; DateTimeFormatInfo DateTimeFormat = CultureInfo.InvariantCulture.DateTimeFormat; Response.Write(dt.ToString(DateTimeFormat.SortableDateTimePattern));
Try it and give us your feedback.
Regards,Hajan
Try to store the datetime like this:
string dt; string dt2; DateTime date = DateTime.Now; DateTime date2 = DateTime.Now; dt = date.ToLongTimeString(); dt2 = date2.ToShortDateString(); cmd.Parameters.Add("@date_time", SqlDbType.NVarChar, 50).Value = string.Concat(dt2, " ", dt); // display format: 20/06/2010 4:58:42
Gjorgji Dimitrov
Posted: 6/21/2011
Actualy i have datetime datatype field in my table i.e joindate
& you r using nvarchar which i don't want. i am using 3 tire architecture where
after formating a date i have to store that date in to another date object.
when i am inserting joindate field of a table using store procedure it works
but when inserting without store proc it dosen't work Why it is so?
I'll give you a little explanataion about this behavior.
Reference: http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.htmlThe differences in date handling can cause problems for developers who use invalid dates. Invalid MySQL dates cannot be loaded into native .NET DateTime objects, including NULL dates.
Because of this issue, .NET DataSet objects cannot be populated by the Fill method of the MySqlDataAdapterclass as invalid dates will cause a System.ArgumentOutOfRangeException exception to occur.
The best solution to the date problem is to restrict users from entering invalid dates. This can be done on either the client or the server side.
Restricting invalid dates on the client side is as simple as always using the .NET DateTime class to handle dates. The DateTime class will only allow valid dates, ensuring that the values in your database are also valid. The disadvantage of this is that it is not useful in a mixed environment where .NET and non .NET code are used to manipulate the database, as each application must perform its own date validation.
Users of MySQL 5.0.2 and higher can use the new traditional SQL mode to restrict invalid date values. For information on using the traditional SQL mode [see ALLOW_INVALID_DATES mode]:
ALLOW_INVALID_DATES
Although it is strongly recommended that you avoid the use of invalid dates within your .NET application, it is possible to use invalid dates by means of the MySqlDateTime datatype.
The MySqlDateTime datatype supports the same date values that are supported by the MySQL server. The default behavior of Connector/NET is to return a .NET DateTime object for valid date values, and return an error for invalid dates. This default can be modified to cause Connector/NET to return MySqlDateTime objects for invalid dates.
To instruct Connector/NET to return a MySqlDateTime object for invalid dates, add the following line to your connection string:
Allow Zero Datetime=True
When using a MySqlDataReader, use the .IsDBNull method to check whether a value is NULL before making the assignment:
Reference: http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html
if (! myReader.IsDBNull(myReader.GetOrdinal("yourtime"))) myTime = myReader.GetDateTime(myReader.GetOrdinal("yourtime")); else myTime = DateTime.MinValue;
NULL values will work in a dataset and can be bound to form controls without special handling.
Hi Gjorgji,
i have done those settings but still it dosen't work
"server=localhost;User Id=root;database=rubicube_db;Allow Zero Datetime=True;Password=root;"
i noticed that My sql stores datetime in a format yyyy-mm-dd HH:mm:ss
& c# stores DateTime.Now ->dd/mm/yyyy HH:mm:ss
pallavi karpe said: Hi Gjorgji,i have done those settings but still it dosen't work "server=localhost;User Id=root;database=rubicube_db;Allow Zero Datetime=True;Password=root;"i noticed that My sql stores datetime in a format yyyy-mm-dd HH:mm:ss& c# stores DateTime.Now ->dd/mm/yyyy HH:mm:ss
Pallavi, then try to directly format it similar to the previous ways we have shown.
Example:
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
Posted: 6/22/2011
Hi Hajan,
it's solve my date issue i have just use this
But really thanks a lot to both of you
becoz from this discussion i come to know more functions about date
Thanks
Posted: 6/25/2011
pallavi karpe said: Hi Hajan,it's solve my date issue i have just use this DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); But really thanks a lot to both of youbecoz from this discussion i come to know more functions about dateThanksPallavi
Always welcome! ;)
Posted: 7/6/2011
use DateTime.ParseExact(date1, "DateFormat", CultureInfo.InvariantCulture);
"DateFormat"
, CultureInfo.InvariantCulture);