Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

c# - Set DateTime format

I have the following code -

DateTime timeStamp;

timeStamp = System.Convert.ToDateTime(y.InnerText);

Where y.InnerText is 11/03/2013 11:35:24.

However this is breaking my import statement as it the database is looking for the format -

2013-03-11 11:35:24

How can I set the format of the DateTime object?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

How can I set the format of the DateTime object?

You can't. DateTime values don't have formats, any more than int or double values do. When you want to convert them to/from strings, that's where you specify any formatting information.

Instead, you should use parameterized SQL and avoid converting the DateTime value back into a string in the first place. This is a general best practice - don't include values in your SQL string; parameterized SQL has multiple benefits:

  • It avoids SQL injection attacks
  • It avoids conversion issues like this one
  • It keeps your code (SQL) separate from your data (parameter values)

I would also suggest that instead of using Convert.ToDateTime, you specify your expected format when parsing. For example:

timeStamp = DateTime.ParseExact(y.InnerText,
                                "dd/MM/yyyy HH:mm:ss",
                                CultureInfo.InvariantCulture);

Basically, the two rules I try to apply are:

  • Avoid performing any conversions where you don't have to. If you make sure that every system uses the right data types as far as possible, you often don't need to make any conversions at all.
  • Where you do need to convert to/from string representations, be very explicit about the representation you want to consume/produce. For machine-readable values, that should usually use the invariant culture and possibly a custom date/time format. For human-readable values, that should usually use the user's culture and a standard date/time format.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...