From 38edbe6e19c79a005b13370a6320fc3dd916ab4f Mon Sep 17 00:00:00 2001 From: Wing-Kam Wong Date: Thu, 18 May 2023 16:15:04 +0800 Subject: [PATCH] feat(nocodb): handle mssql database timezone --- packages/nocodb/src/db/BaseModelSqlv2.ts | 12 ++++++++++++ packages/nocodb/src/models/Model.ts | 10 +++++++--- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/packages/nocodb/src/db/BaseModelSqlv2.ts b/packages/nocodb/src/db/BaseModelSqlv2.ts index a50534be70..4247742f1f 100644 --- a/packages/nocodb/src/db/BaseModelSqlv2.ts +++ b/packages/nocodb/src/db/BaseModelSqlv2.ts @@ -1647,6 +1647,18 @@ class BaseModelSqlv2 { .wrap('(', ')'); break; } + } else if (this.isMssql) { + // if there is no timezone info, convert to database timezone, then convert to UTC + if (column.dt !== 'datetime2') { + const col = `${sanitize(alias || this.model.table_name)}.${ + column.column_name + }`; + res[sanitize(column.title || column.column_name)] = + this.dbDriver.raw( + `SWITCHOFFSET(??, DATEPART(TZOFFSET, ??)) AT TIME ZONE 'UTC'`, + [col, col], + ); + } } res[sanitize(column.title || column.column_name)] = sanitize( `${alias || this.model.table_name}.${column.column_name}`, diff --git a/packages/nocodb/src/models/Model.ts b/packages/nocodb/src/models/Model.ts index e9d552d764..77c825f617 100644 --- a/packages/nocodb/src/models/Model.ts +++ b/packages/nocodb/src/models/Model.ts @@ -506,10 +506,14 @@ export default class Model implements TableType { ]); } else if (isMssql) { // e.g. 2023-05-10T08:49:32.000Z -> 2023-05-10 08:49:32-08:00 - val = dayjs(val).utc().format('YYYY-MM-DD HH:mm:ssZ'); + // then convert to db timezone + val = knex.raw( + `SWITCHOFFSET(? AT TIME ZONE 'UTC', SYSDATETIMEOFFSET()`, + [dayjs(val).utc().format('YYYY-MM-DD HH:mm:ssZ')], + ); } else { - // e.g. 2023-01-01T12:00:00.000Z -> 2023-01-01 20:00:00+08:00 - val = dayjs(val).format('YYYY-MM-DD HH:mm:ssZ'); + // e.g. 2023-01-01T12:00:00.000Z -> 2023-01-01 12:00:00+00:00 + val = dayjs(val).utc().format('YYYY-MM-DD HH:mm:ssZ'); } } insertObj[sanitize(col.column_name)] = val;