我是 C# 的新手,我对 System.Globalization.CultureInfo 类的工作方式有以下疑问。
我有以下情况。
在一个类中,我读取了一些值(从使用 XPath 的 XML 中),其中包含一些信息作为一些数据字段。
所以我有类似的东西:
System.Globalization.CultureInfo cultureEN = new System.Globalization.CultureInfo("en-GB");
currentDeepSightVuln.LastUpdated = DateTime.Parse(n_alertdocument.SelectSingleNode("./x:LastUpdated", nsmgr).InnerText, cultureEN);
在我的 XML 文件中,这个字段是:
<x:LastUpdated>2014-05-21T17:00:38</x:LastUpdated>
所以它的值为2014-05-21T17:00:38
在执行上一个操作(初始化 LastUpdate 对象属性)时运行我的程序 我的 **LastUpdate 属性值为:{21/05/2014 17: 00:38.
如您所见,它具有不同于 XML 字段值的另一种格式。我认为这是很正常的,因为它是根据 en-GB 设置转换的。
我的疑问是:如果我将我的对象保存在数据库表 (Microsoft SQL Server) 上,我会遇到一些问题还是它会以正确的形式从 SQL Server 中重新转换?
编辑 1: 为了将我的对象插入数据库,我使用类似的东西:
公共(public)长插入(DataModel.Vulnerability.Vuln v) {
_strSQL = "";
string strSQLParametri = "";
string query = "";
long newId;
long VulnerabilityAlertDocumentPkValue;
System.Data.Common.DbCommand command;
command = _connection.CreateCommand();
try
{
_transactionBegin();
// [VulnerabilityAlertId] insertion on the DB:
if (v.VulnerabilityAlertId != null)
{
_strSQL = "INSERT INTO VulnerabilityAlertDocument ( [VulnerabilityAlertId] ";
strSQLParametri = " VALUES (@VULNERABILITYALERTID ";
_addParameter(command, "@VULNERABILITYALERTID ", newId);
}
........................................................................
........................................................................
........................................................................
_strSQL += ",[PUBLISHED] ";
strSQLParametri += ", @PUBLISHED ";
_addParameter(command, "@PUBLISHED", v.Published);
........................................................................
........................................................................
........................................................................
query = _strSQL + " ) " + strSQLParametri + " );";
command.CommandText = query;
_executeNoQuery(command);
VulnerabilityAlertDocumentPkValue = _getIdentity();
Debug.WriteLine("PK della tabella VulnerabilityAlertDocumentPkValue: " + VulnerabilityAlertDocumentPkValue);
谢谢
最佳答案
这实际上与文化无关,与 en-GB 无关,与 SQL Server 无关;更简单地说,xml 按照 ISO 8601 格式定义日期。到此结束。
您不应使用 DateTime.Parse
指定 en-GB
和 xml。这是不正确的。
正确的实现应该是:
DateTime when = XmlConvert.ToDateTime(...);
或者更方便的是,如果使用 XElement
等:
DateTime when = (DateTime)el;
如果您想从 xml 远离谈论 SQL server 中的日期,那么只需:将它们视为 date
或 datetime
(而不是strings) - 通过类型化列或作为类型化参数。这样就不会在格式或语言环境方面产生任何混淆。
通过您的编辑,这再次与 xml 无关。假设 v.Published
是一个 DateTime
,而 [PUBLISHED]
是一个 datetime
,那么它应该可以正常工作- 这些值绝不是字符串。 DateTime
/datetime
实际上是一个数字(某个定义的时间间隔到定义的纪元)。由于它们永远不是字符串,因此:文化和格式不涉及。
关于c# - 关于C# CultureInfo 和SQL Server 关系的一些疑惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24138251/