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
1.0k views
in Technique[技术] by (71.8m points)

string to DateTime conversion in C#

Stupid questions but cant get my head around it... I have a string in this format 20081119

And I have a C# method that converts the string to a DateTime to be entered into a SQL Server DB

public static DateTime MyDateConversion(string dateAsString)
    {

        return System.DateTime.ParseExact(dateAsString, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);

    }

The problem is that the Date is coming out like this: Date = 19/11/2008 12:00:00 AM and I need it to be a DateTime of type yyyyMMdd as I am mapping it into a schema to call a stored proc.

Thanks in advance guys.

Cheers, Con

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

There is no such thing as "a DateTime of type yyyyMMdd"; a DateTime is just a large integer, indicating the amount of time in an epoch - it doesn't have a format. But that is fine, since you should be using parametrized TSQL anyway - so just add the DateTime as the value of a DbParameter, and it will be handed to the db in an unambiguous way (don't use string concatenation to build a TSQL command):

DbParameter param = cmd.CreateParameter();
param.ParameterName = "@foo";
param.DbType = DbType.DateTime;
param.Value = yourDateTime; // the DateTime returned from .ParseExact
cmd.Parameters.Add(param);

or for a SqlCommand:

cmd.Parameters.Add("@foo", SqlDbType.DateTime).Value = yourDateTime;

If you genuinely need a string, then just use the string directly as a [n][var]char parameter.

Also - in this case, to parse the date I would use the invariant culture (since culture doesn't feature in the format):

DateTime yourDateTime =
            DateTime.ParseExact(dateString, "yyyyMMdd", CultureInfo.InvariantCulture);

From the conversation, it seems you might also need to go from a DateTime to a string, in which case simply reverse it:

string dateString = yourDateTime.ToString("yyyyMMdd", CultureInfo.InvariantCulture);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
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

...