简体   繁体   English

将dd / mm / yyyy中的日期时间字符串转换为日期时间格式mm / dd / yyyy

[英]Convert date time string in dd/mm/yyyy to datetime format mm/dd/yyyy

There is an input from CSV file which is in dd/mm/yyyy format. CSV文件有一个输入,格式为dd / mm / yyyy。 I have to pass these date values to the stored procedure. 我必须将这些日期值传递给存储过程。 I want to convert this to mm/dd/yyyy format before I bulkcopy it to the database table from the datatable in the c# code. 我想先将其转换为mm / dd / yyyy格式,然后再将其从C#代码的数据表中批量复制到数据库表中。

Should I do this in the code or in the stored procedure which I am sending it to? 我应该在发送它的代码或存储过程中执行此操作吗? Please advise.I have tried all possible combinations. 请告知。我尝试了所有可能的组合。

You could you use DateTime.ParseExact , 您可以使用DateTime.ParseExact

var parsedDate = DateTime.ParseExact(dateString, "dd/MM/YYYY", CultureInfo.InvariantCulture);

where dateString is the string representation of the date you want to parse. 其中dateString是要解析的日期的字符串表示形式。

If your stored procedures expects a DateTime you could use the parseDate value. 如果您的存储过程期望使用DateTime,则可以使用parseDate值。 Otherwise, if it expects a string in the format you mentioned, you can pass the following value: 否则,如果期望使用您提到的格式的字符串,则可以传递以下值:

parsedDate.ToString("MM/dd/YYYY")

您应该在C#中将值解析为DateTime并将此日期值传递给SQL客户端或ORM,而不必将其转换为字符串

If your SQL field type is set to either one of the date value types it is quite impossible to format the date according to your desire, since the database engine does not store the formatted value but the date value itself. 如果您的SQL字段类型设置为日期值类型之一,则完全不可能根据您的需要格式化日期,因为数据库引擎不存储格式化的值,而是存储日期值本身。

Make sure to parse the DateTime in-code before updating its value in the SQL database. 确保在更新SQL数据库中的值之前先解析DateTime代码。

string date = "2000-02-02";
DateTime time = DateTime.Parse(date); // Will throw an exception if the date is invalid.

There's also the TryParse method available for you. 还提供了TryParse方法。 It will make sure the date value you're trying to parse is indeed in the right format. 它将确保您尝试解析的日期值的格式确实正确。

string input = "2000-02-02";
DateTime dateTime;
if (DateTime.TryParse(input, out dateTime))
{
    Console.WriteLine(dateTime);
}

After the storage you're more than welcome to select your preffered display format for your DateTime variable using one of the given formats (read link below for a full list of available formats). 存储之后,非常欢迎您使用给定的格式之一为DateTime变量选择您喜欢的显示格式(请参阅下面的链接以获取可用格式的完整列表)。

https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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