You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

BizTalk 2013R2中如何将字符串转DateTime以适配SQL Server?

处理BizTalk中SQL Server日期映射的格式问题

多数BizTalk集成场景需要将数据写入SQL Server数据库,目前我接收其他应用的XSLT直接消息,再映射到SQL Server存储过程。其中有4个日期字段需要映射,我用映射functoid写了以下转换代码:

public string StringToDatetime(string input)
{
    DateTime dt;

    if (DateTime.TryParse(input, out dt))
    {
        return dt.ToString("yyyy-MM-dd");
    }
    else
    {
        return "";
    }
}

无论尝试将dt格式化为哪种形式(包括ISO 8601格式),都会反复收到以下错误:

Failed to convert parameter value from a String to a DateTime.
System.FormatException: String was not recognized as a valid DateTime.

输入值示例:

<date_of_birth>1996-05-04T00:00:00Z</date_of_birth>

标准解决方法

  • 精准解析带时区的日期字符串:输入是带UTC标识Z的ISO 8601格式,DateTime.TryParse依赖系统区域设置,容易解析失败。改用DateTime.TryParseExact指定格式和不变文化,确保解析准确:

    public object StringToDatetime(string input)
    {
        DateTime dt;
        // 匹配带Z的ISO 8601格式,指定不变文化和UTC调整
        if (DateTime.TryParseExact(input, "yyyy-MM-ddTHH:mm:ssZ", 
            System.Globalization.CultureInfo.InvariantCulture, 
            System.Globalization.DateTimeStyles.AdjustToUniversal, out dt))
        {
            // 直接返回DateTime对象,避免字符串转换;若需字符串则返回SQL兼容格式
            return dt;
            // 若必须返回字符串:return dt.ToString("yyyy-MM-dd HH:mm:ss");
        }
        else
        {
            // 返回DBNull而非空字符串,避免SQL参数类型不匹配
            return DBNull.Value;
        }
    }
    
  • 优先传递DateTime类型参数:如果存储过程的日期参数是DateTime类型,尽量直接传递解析后的DateTime对象,而非转换为字符串。这样能彻底规避格式转换错误,BizTalk会自动处理参数类型映射。

  • SQL Server端兜底转换:如果只能传递字符串,可在存储过程中用CONVERT指定格式解析:

    -- 120对应yyyy-MM-dd HH:mm:ss的ISO格式
    SET @targetDate = CONVERT(DATETIME, @inputDateStr, 120)
    

内容的提问来源于stack exchange,提问作者mrc85

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 11:42:06