C#中字符串到日期时间的转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/336226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 23:42:27  来源:igfitidea点击:

string to DateTime conversion in C#

c#

提问by

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

愚蠢的问题,但我无法理解……我有一个这种格式的字符串 20081119

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

我有一个 C# 方法可以将字符串转换为 DateTime 以输入到 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.

问题是 Date 是这样出来的:Date = 19/11/2008 12:00:00 AM,我需要它是一个 yyyyMMdd 类型的 DateTime,因为我将它映射到一个模式来调用一个存储过程。

Thanks in advance guys.

在此先感谢各位。

Cheers, Con

干杯,骗子

回答by johnc

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

日期时间是一个类,默认情况下,它的 ToString 格式为 19/11/2008 12:00:00 AM

This is from MSDNwhich may help you

这是来自MSDN可能对您有所帮助

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.

由于日期和时间值的外观取决于文化、国际标准、应用程序要求和个人偏好等因素,因此 DateTime 结构通过其 ToString 方法的重载在格式化日期和时间值方面提供了很大的灵活性。默认的 DateTime.ToString() 方法使用当前区域性的短日期和长时间模式返回日期和时间值的字符串表示形式。下面的示例使用默认的 DateTime.ToString() 方法使用短日期和长时间模式为 en-US 区域性显示日期和时间,即运行该示例的计算机上的当前区域性。

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

因此,您可以将 DateTime 上的 ToString 重载为所需的格式,否则将字符串表示直接传递给存储过程

回答by Marc Gravell

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

没有“yyyyMMdd 类型的日期时间”这样的东西;DateTime 只是一个大整数,表示一个纪元中的时间量 - 它没有格式。但这很好,因为无论如何您都应该使用参数化的 TSQL - 所以只需将 DateTime 添加为 DbParameter 的值,它将以明确的方式传递给数据库(不要使用字符串连接来构建 TSQL 命令):

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:

或为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.

如果您真的需要一个字符串,那么只需将该字符串直接用作 [n][var]char 参数。

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:

从对话中,您似乎还需要从 DateTime 转到字符串,在这种情况下只需将其反转即可:

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

回答by Andrew Van Slaars

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:

我认为这是由于 CurrentCulture 中设置的文化,不知道那是什么,我不能确定,但​​指定 en-US 对我来说是有效的。这是我的代码:

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.

试一试,看看它是否适合你。

回答by Samiksha

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

这将给出您正在寻找的确切结果:

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

convert( varchar(10), getdate(), 112 ) : 日期时间到字符串(YYYYMMDD 格式)

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

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

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)

DateTimeFormatInfo fmt = (new CultureInfo("hr-HR")).DateTimeFormat; Console.WriteLine(thisDate.ToString("d", fmt)); // 显示 15.3.2008(根据您的要求使用类似的格式)

or

或者

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

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

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

详情请见http://msdn.microsoft.com/en-us/library/az4se3k1.aspx

回答by Andrew Van Slaars

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

好的,回到文化问题......当你说:

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

日期是这样出来的:日期 = 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.

我猜你在日期运行 ToString 来查看这个结果?ToString 中的格式将根据文化而有所不同,默认情况下将使用您当前的文化。

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.

我可能会误读你的问题,但我不得不把它弄出来 b/c 它让我烦恼。