目标
使用 Oracle 日期时间格式[1](如“IY-IW”)将 DateTime
转换为 string
。
描述
我有一种情况,我得到了一个 DateTime
和一个 Oracle 日期格式字符串。
结果应该是一个字符串
,其中包含采用 Oracle 日期格式指定的格式的日期和时间。
简而言之,我需要下面的方法
/// <summary>
/// Converts a datetime to a string with the format specified by the Oracle date format.
/// </summary>
/// <param name="oracleDateFormat">
/// Datetime format specified in http://www.techonthenet.com/oracle/functions/to_char.php
/// </param>
/// For example:
/// dateTimeToConvert = 2014-09-23T10:09:47.7739125+02:00, oracleNlsDateFormat = "IY-IW" => result == "14-38"
public string ConvertDateTimeToString(DateTime dateTimeToConvert, string oracleDateFormat);
如果在数据库查询中完成,我会使用 Oracle to_char 方法。但是,我需要在 C# 环境中进行转换。
- C# How to parse a string of date in an arbitrary specified Oracle date format?
- How to format a date from Oracle to a valid datetime in c#
上面的问题都在正确的轨道上,但仍然没有解决我的问题。例如,提供格式为“IY-IW”的 DateTime.ParseExact 会引发 FormatException。
有没有简单的方法可以达到目的?就像使用 DateTime.ParseExact 并以某种方式指定使用 Oracle 日期格式一样?或者以某种方式将 Oracle 日期时间格式转换为 C# 日期时间格式[2]?
如果是,该解决方案会是什么样子?
注释和引用
- Oracle 日期格式规范:http://www.techonthenet.com/oracle/functions/to_char.php
- 创建一个将 Oracle 日期时间格式映射到 C# 日期时间格式的方法是可能的,但我认为这不是一个好的或简单的解决方案。
最佳答案
Is there a simple way to achieve the goal?
几乎可以肯定不是。
Like using DateTime.ParseExact and somehow specifying that an Oracle date format is used?
否 - .NET 不了解 Oracle 日期/时间格式。
Converting the Oracle datetime format to C# datetime format on some way?
这是我的第一个建议。特别是:
- 如果您只需要支持这些格式中的一小部分,可能值得对您支持的格式进行硬编码
- 即使您需要比这更灵活一点,我也不会尝试支持 Oracle 支持的一切
- 您可能仍会遇到有关
IW
或其他基于周的格式的重大问题。 (DateTime
不支持 ISO 周-年。)
不过,我会尝试首先删除该要求。尽可能首先避免将日期编码为字符串 - 如果您向数据库提供日期,请将其作为 DateTime
或 DateTimeOffset
通过参数。我们对您的上下文了解不多,无法确定这是否是一个选项,但如果可以的话,花一些时间尝试删除该要求是值得的。
关于c# - 如何使用 Oracle 日期格式将 DateTime 转换为 C# 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25991179/