Loading ...

How to convert string to datetime?

Who is online?  0 guests and 0 members
home  »  forums   »  asp.net topics   »  client side web development   » How to convert string to datetime?

How to convert string to datetime?

Posts under the topic: How to convert string to datetime?

Posted: 6/16/2011

Lurker 245  points  Lurker
  • Joined on: 4/15/2011
  • Posts: 44

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

Starter 727  points  Starter
  • Joined on: 6/6/2011
  • Posts: 74

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

 


tags DateTime

Posted: 6/17/2011

Professional 8505  points  Professional
  • Joined on: 5/3/2010
  • Posts: 391

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!");
            }

Hope this helps,
Hajan


Posted: 6/17/2011

Lurker 245  points  Lurker
  • Joined on: 4/15/2011
  • Posts: 44

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


Posted: 6/17/2011

Starter 727  points  Starter
  • Joined on: 6/6/2011
  • Posts: 74

Hi 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

Regards,

Gjorgji


tags DateTime

Posted: 6/17/2011

Professional 8505  points  Professional
  • Joined on: 5/3/2010
  • Posts: 391

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

Lurker 245  points  Lurker
  • Joined on: 4/15/2011
  • Posts: 44

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

 


Posted: 6/20/2011

Professional 8505  points  Professional
  • Joined on: 5/3/2010
  • Posts: 391

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


Posted: 6/20/2011

Starter 727  points  Starter
  • Joined on: 6/6/2011
  • Posts: 74

Hi Pallavi,

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

One more thing i've notice above, if you are using String.Format, capitalize HH's otherwise times after 12 noon will not be entered correctly. 

Best Regards,

Gjorgji Dimitrov


Posted: 6/21/2011

Lurker 245  points  Lurker
  • Joined on: 4/15/2011
  • Posts: 44

Hi Gjorgji,Hajan

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?

 

 

 


Posted: 6/21/2011

Starter 727  points  Starter
  • Joined on: 6/6/2011
  • Posts: 74
  Answered

Hi Pallavi,

I'll give you a little explanataion about this behavior.

 


Reference: http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html

The 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]:

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.

 

Best Regards,

Gjorgji Dimitrov


tags MySql

Posted: 6/21/2011

Lurker 245  points  Lurker
  • Joined on: 4/15/2011
  • Posts: 44

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


Posted: 6/21/2011

Professional 8505  points  Professional
  • Joined on: 5/3/2010
  • Posts: 391
  Answered

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");

Hope this helps,
Hajan


Posted: 6/22/2011

Lurker 245  points  Lurker
  • Joined on: 4/15/2011
  • Posts: 44

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 you

becoz from this discussion i come to know more functions about date

Thanks

Pallavi  Smile


Posted: 6/25/2011

Professional 8505  points  Professional
  • Joined on: 5/3/2010
  • Posts: 391

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 you

becoz from this discussion i come to know more functions about date

Thanks

Pallavi  Smile

Always welcome! ;)


Posted: 7/6/2011

Lurker 125  points  Lurker
  • Joined on: 5/24/2011
  • Posts: 9

use DateTime.ParseExact(date1, "DateFormat", CultureInfo.InvariantCulture);


Page 1 of 1 (16 items)