C# 将中的字符串转换为SQL Server中的DateTimeoffset

C# 将中的字符串转换为SQL Server中的DateTimeoffset,c#,sql,biztalk,psql,biztalk-2013,C#,Sql,Biztalk,Psql,Biztalk 2013,我正在尝试从psql数据库中提取数据,并使用BizTalk将它们插入SQL Server数据库。psql中有一列名为createddate,类型为TimeStamp,时区为6/30/2016 12:00:00 AM 我想将该数据插入类型为datetimeoffset的SQL Server列DateCreated。由于我使用的是BizTalk,所有数据都作为sting处理,因此我使用如下脚本 public string ConvertDateCreated(string dateCreated)

我正在尝试从psql数据库中提取数据,并使用BizTalk将它们插入SQL Server数据库。psql中有一列名为
createddate
,类型为
TimeStamp
,时区为
6/30/2016 12:00:00 AM

我想将该数据插入类型为
datetimeoffset
的SQL Server列
DateCreated
。由于我使用的是BizTalk,所有数据都作为sting处理,因此我使用如下脚本

public string ConvertDateCreated(string dateCreated)
{
     System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
     return DateTime.ParseExact(dateCreated, "MMddyyyy", provider).ToString("yyyyMMdd");
} 

但这是一个错误:

字符串未被识别为有效的日期时间

异常类型:FormatException
来源:mscorlib
目标站点:System.DateTime ParseExact(System.String、System.String、System.Globalization.DateTimeFormatInfo、System.Globalization.DateTimeStyles)

以下是识别异常发生位置的堆栈跟踪

位于System.DateTimeParse.ParseExact(字符串s、字符串格式、DateTimeFormatInfo dtfi、DateTimeStyles样式)
位于System.Xml.Xsl.CompiledQuery.Script1.ConvertDateCreated(String dateCreated)
在(XmlQueryRuntime{urn:schemas-microsoft-com:xslt-debug}运行时,XPathNavigator{urn:schemas-microsoft-com:xslt-debug}当前)
在(XmlQueryRuntime{urn:schemas-microsoft-com:xslt-debug}运行时,XPathNavigator{urn:schemas-microsoft-com:xslt-debug}当前)
在根(XmlQueryRuntime{urn:schemas-microsoft-com:xslt-debug}运行时)
在执行时(XmlQueryRuntime{urn:schemas-microsoft-com:xslt-debug}运行时)
在System.Xml.Xsl.XmlILCommand.Execute(对象defaultDocument、XmlResolver数据源、XslTargetList argumentList、XmlSequenceWriter结果)
在System.Xml.Xsl.XmlILCommand.Execute(对象defaultDocument、XmlResolver数据源、XslTargetList argumentList、XmlWriter writer)上执行
在System.Xml.Xsl.xslcomiledTransform.Transform(IXPathNavigable输入、XSLTargetList参数、XmlWriter结果、XmlResolver documentResolver)


对于ParseExact,源日期格式应该类似于
“M/dd/yyyy hh:mm:ss tt”


适用于时区sql server datetimeoffset类型的格式为:

c.CreationDateTime=DateTime.ParseExact(rdr[“CreationDateTime”].ToString(),
“年月日HH:MM:ss zzz”,
文化信息(不变量文化);

首先,您需要获取psql日期时间的日期时间格式
“M/d/yyyy hh:mm:ss tt”

然后使用
DateTimeOffset
解析您的
psql datetime

public static string ConvertDateCreated(string dateCreated)
    {
        System.Globalization.CultureInfo provider =  System.Globalization.CultureInfo.InvariantCulture;
        return DateTimeOffset.ParseExact(dateCreated, "M/d/yyyy hh:mm:ss tt", provider).ToString();
    }
要检查结果,请使用sql
datetimeoffset

select cast('6/30/2016 12:00:00 AM +00:00' as datetimeoffset)
    

试试.NET fiddle

你有从原始数据库返回的日期字符串的示例吗?就像
2016年6月30日12:00:00 AM
那么你的格式应该是
dd/MM/yyyyy HH:MM:ss
@PaulF在原始数据库中就像
2016年6月30日12:00:00 AM
你可能需要修改精确的格式来匹配-就像这样与“MMddyyyy”不同。
select cast('6/30/2016 12:00:00 AM +00:00' as datetimeoffset)