使用 VB 脚本将 varchar 转换为 datetime

Convert varchar to datetime using VB script

我需要使用 .Net 将 varchar 格式的日期字段 (DDMMYYYY) 转换为 DateTime。我尝试了多种解决方案,但都无济于事。该字段的源是平面文件,目标是 table。我正在使用 SSIS 包中的脚本。

示例如下:

SampleDate 列采用 ddmmyyyy 格式。我正在将其转换为 MM/dd/YYYY,以便将其转换为日期时间格式。

Dim retString1 As String
Dim slash As Char = ChrW(&H2F)
retString1 = Row.SampleDate.Substring(2, 2) & "/"
Dim retString2 As String
retString2 = Row.SampleDate.Substring(0, 2) & "/"
Dim retString3 As String
retString3 = Row.SampleDate.Substring(4, 4)
Dim retString4 As String
retString4 = retString1 & retString2 & retString3

Dim fromDt As Date = Convert.ToDateTime(retString4)
fromDt = Row.SampleDate

P.S。 :我不是在寻找 SQL 转换查询,所以在评论之前,请通读整个问题。我正在寻找 VB 代码而不是 SQL 代码。

要在 VBScript 中将字符串转换为日期,您可以使用 CDate() 哪个为您进行转换,但取决于当前的区域设置或 DateSerial():

>> s = "13041953"
>> d = DateSerial(CInt(Right(s,4)), CInt(Mid(s,3,2)), CInt(Left(s,2)))
>> WScript.Echo s, TypeName(d), d
>>
13041953 Date 13.04.1953 (german locale)

只需翻转fromdt = Row.SampleDate

Row.SampleDate = fromdt

您的脚本应该可以运行,但如果您愿意,请参阅下文以简化一些脚本。

如何在没有脚本的情况下执行此操作 -- 请参阅下面的脚本方法

如果您改为使用 Derived Column 转换,您可以自己简化很多事情!数据转换转换不起作用,因为它不允许您操作列的值,而只能操作数据类型。但是在派生列中,您可以分割字符串并将结果转换为日期。

因此在您的数据流中从源到派生列到目标。

在派生列中添加一个新列并使用以下表达式(将 DateString 替换为包含 ddMMyyyy 格式日期的 name of your column

然后用这个作为 Expression:

(DT_DATE)(SUBSTRING(DateString,3,2) + "/" + (LEFT(DateString,2) + "/" + RIGHT(DateString,4)))

如果您愿意,可以将 (dt_date) 切换为另一种日期格式,该类型转换将自动在 Derived Column 上设置 Data Type。然后在您的 destination 中将 new derived column 映射到 destination column 而不是 source.

中的原始列

大功告成,没有脚本。

如何通过脚本实现

如果您想继续使用脚本并可能注入一些额外的逻辑而不是简单的转换来解决路由问题,您可以通过 transformation script component 在您的 data flow task.它将取代上面的 derived column 转换,但本质上只会通过脚本做同样的事情。我在这里放一些步骤,我猜你已经知道一些以防其他人偶然发现 post.

  • 选择 "transformation" 时添加脚本组件并将其与您的源连接
  • 打开脚本组件并转到“Inputs and Outputs”部分并添加一个输出以保存新列并设置数据类型。需要一个新列,因为您正在更改数据类型

  • 转到“Input Columns”部分并选择 SampleDate

  • 返回“Script”部分并选择 Visual Basic 作为您的脚本语言。
  • 单击“编辑脚本”开始编码。
  • 向下滚动直到找到子 Input0_ProcessInputRow(ByVal Row... 这是放置代码的地方。

此代码有效:

Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)

    If Not Row.SampleDate_IsNull Then

        Row.DerivedDate = DateTime.ParseExact(Row.SampleDate, "ddMMyyyy", System.Globalization.CultureInfo.InvariantCulture)

    End If
End Sub

@Shiva 在评论中建议您可以扩展它并使用 TryParseExact 或将其包装在 try catch 块中,这样如果解析日期失败,它只会 clear/remove 记录中的值并且导入将继续。我把这个留给你,因为处理无效数据更多是业务需求的问题。