简体   繁体   中英

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

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

Date Time is a class that, by default, formats it's ToString as 19/11/2008 12:00:00 AM

This is from MSDN which may help you

Because the appearance of date and time values is dependent on such factors as culture, international standards, application requirements, and personal preference, the DateTime structure offers a great deal of flexibility in formatting date and time values through the overloads of its ToString method. The default DateTime.ToString() method returns the string representation of a date and time value using the current culture's short date and long time pattern. The following example uses the default DateTime.ToString() method to display the date and time using the short date and long time pattern for the en-US culture, the current culture on the computer on which the example was run.

You may be able, therefore, to overload the ToString on DateTime to the desired format, else pass the string representation directly to the stored procedure instead

Ok, back to the culture thing... When you say:

the Date is coming out like this: Date = 19/11/2008 12:00:00 AM

I'm guessing you are running a ToString on the date to see this result? The formatting in ToString will vary based on the culture and will use your current culture by default.

I was able to reproduce the format your are getting by doing this:

var dateString = "20081119";
var fr = new System.Globalization.CultureInfo("fr-FR");
var resultingDate =DateTime.ParseExact(dateString,"yyyyMMdd",System.Globalization.CultureInfo.CurrentCulture);
Console.WriteLine(resultingDate.ToString(fr));

You have a valid date, so the formatting shouldn't matter, but if it does and you need to get it in the format you described, then you need to format it when converting to a string... if it's already a string, then there is no need for the date conversion.

I could be mis-reading your question, but I had to get this out b/c it was bugging me.

I'm thinking it's due to the culture set in CurrentCulture, without knowing what that is, I can't be certain, but specifying en-US works on my end. Here is the code I have:

var dateString = "20081119";
var enUS = new System.Globalization.CultureInfo("en-US");
var resultingDate = DateTime.ParseExact(dateString,"yyyyMMdd",enUS);
Console.WriteLine(resultingDate.ToString());

Give it a try and see if it works for you.

This is what will give exact result you are looking for:

convert( varchar(10), getdate(), 112 ) : datetime to string (YYYYMMDD format)

convert( datetime, '20081203', 112 ) : string to datetime (YYYYMMDD format)

Code side:

DateTimeFormatInfo fmt = (new CultureInfo("hr-HR")).DateTimeFormat; Console.WriteLine(thisDate.ToString("d", fmt)); // Displays 15.3.2008 (use similar formats acc to your requirements)

or

date1.ToString("YYYYMMDD",CultureInfo.CreateSpecificCulture("en-US")) date1.ToString("YYYYMMDD");

Details at http://msdn.microsoft.com/en-us/library/az4se3k1.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM