字符串在C#中的DateTime转换 [英] string to DateTime conversion in C#

查看:227
本文介绍了字符串在C#中的DateTime转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

愚蠢的问题,但不能让我的头周围...
我在这个格式的字符串20081119

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

和我有一个C#方法转换字符串为DateTime要输入到一个SQL Server数据库

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

    }

的问题是,日期是走出来是这样的:日期= 19/11/2008 12:00:00 AM,我需要它,因为我映射成一个模式来调用存储过程型年月日的日期时间。

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.

在此先感谢球员。

干杯,
精读

推荐答案

有作为类型YYYYMMDD的日期时间没有这样的事;日期时间仅仅是一个大的整数,表示在一个划时代的时间量 - 它不具有的格式。但是,这是很好的,因为你应该使用反正TSQL参数化 - 所以刚才添加的日期时间为的DbParameter的价值,它会以明确的方式交给分贝(不要使用字符串连接建立一个TSQL命令):

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

或一个的SqlCommand

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

如果你真的需要一个字符串,那么就直接使用字符串作为[N] [VAR] 。炭参数

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

这篇关于字符串在C#中的DateTime转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆