0

I am getting back a date time from MailChimp that has the format yyyy-MM-ddTHH:mm:ss+00:00. An example is 2016-11-14T17:31:19+00:00.

I am not sure how I should reformat this to fit into the SQL Server Datetime format. I am coding in 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 
}
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
user6927085
  • 115
  • 1
  • 8

1 Answers1

0

You should be able to insert the timestamp if you change it to smalldatetime format. The simplest way would be to replace the T with a space, remove the timezone offset, and just insert the UTC timestamp:

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

If you want to be a little more diligent you'd use a more precise regular expression for matching a timestamp: ^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}:\d{2})\+\d{2}:\d{2}$.

If you want to be really diligent you actually parse and re-format the timestamp.

$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');"
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328