将yyyy-MM-ddTHH:mm:ss + 00:00格式化为SQL Server日期时间格式

时间:2016-11-22 16:08:02

标签: sql-server powershell datetime

我从MailChimp获取格式为yyyy-MM-ddTHH:mm:ss+00:00的日期时间。一个例子是2016-11-14T17:31:19+00:00

我不确定如何重新格式化以适应SQL Server Datetime格式。我在PowerShell编码。

#HTTP Get returns datetime from mailchimp in format yyyy-MM-ddTHH:mm:ss+00:00
$MailChimpTimeGMT = Invoke-RestMethod -Method Get -Uri "$URL$endpoint" -Headers $auth -ContentType "application/json"

$formattedTime = ((Get-Date).ToUniversalTime()).ToString("yyyy-MM-ddTHH:mm:ss+00:00")

if ( $formattedTime -lt $MailChimpTimeGMT ) {
  #$DBase and $DBSvr declared
  #
  #Need to convert $MailChimpTimeGMT in match SQL date time format without loss
  #
  $sqlcmd = "INSERT INTO dbo.MAILCHIMP_LISTSERVE (TIME_STAMP,MODIFY_SOURCE)" +
            " VALUES (" +  $MailChimpTimeGMT + ", powershell );"

  $data = Invoke-Sqlcmd -Query $sqlcmd -Database $DBase -ServerInstance $DBSvr 
}

1 个答案:

答案 0 :(得分:0)

如果您将时间戳更改为smalldatetime格式,则应该可以插入时间戳。最简单的方法是用空格替换T,删除时区偏移量,然后只插入UTC时间戳:

$ts = $MailChimpTimeGMT -replace '^(.*?)T(.*?)\+.*', '$1 $2'
$sqlcmd = "INSERT INTO dbo.MAILCHIMP_LISTSERVE (TIME_STAMP, MODIFY_SOURCE)" +
          " VALUES ('$ts', 'powershell');"

如果您想更加勤奋,可以使用更精确的正则表达式来匹配时间戳:^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}:\d{2})\+\d{2}:\d{2}$

如果你想真正勤奋,你实际上parse并重新 - format时间戳。

$infmt   = 'yyyy-MM-ddTHH:mm:sszzz'
$outfmt  = 'yyyy-MM-dd HH:mm:ss'
$culture = [Globalization.CultureInfo]::InvariantCulture

$ts = [DateTime]::ParseExact($MailChimpTimeGMT, $infmt, $culture).ToString($outfmt)
$sqlcmd = "INSERT INTO dbo.MAILCHIMP_LISTSERVE (TIME_STAMP, MODIFY_SOURCE)" +
          " VALUES ('$ts', 'powershell');"