[英]Convert datetime column from utc to local time in a populated datatable
我正在嘗試使用 EPPLUS 在 excel 文件中從 Sql 服務器導出一些數據,並通過自定義 sql Z99938282F040718CF4294 狀態這工作正常,但問題是日期時間字段以 UTC 格式存儲在數據庫中,而不是我想以本地時區格式(es.GMT +2)顯示它們。 有沒有辦法以最小的性能損失來完成? 使用 EPPLUS 方法在數據表或 excel 文件中轉換列都沒有關系。 我希望最終的 output 顯示 +2 小時的時間。
我嘗試添加 DataColumn col.ExtendedProperties.Add("TZ", +2); 但沒有任何改變。 DataColumn.DateTimeMode 不適用於填充的 DataTable。 我正在嘗試用添加 +2 小時的公式替換 excel 列,但我無法弄清楚。 下面你可以看到我的代碼。
string connString = @"Data Source=" + DataSourceName + ";Initial Catalog=" + InitialCatalog + ";User ID=" + UserID + "; Password=" + password + ";Integrated Security=SSPI;";
SqlConnection conn = new SqlConnection(connString);
conn.Open();
//retreive data from the report query
SqlCommand Reportcmd = new SqlCommand(ReportQuery, conn);
Reportcmd.CommandTimeout = 0;
SqlDataAdapter Reportda = new SqlDataAdapter(Reportcmd);
Reportda.Fill(ReportDtTbl);
conn.Close();
//var fileName = "Example-CRM-" + DateTime.Now.ToString("yyyy-MM-dd--hh-mm-ss") + ".xlsx";
MemoryStream stream = new MemoryStream();
using (ExcelPackage pck = new ExcelPackage(stream))
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Report");
Tempaltesheet.Cells[1, 1, 1, 100].Copy(ws.Cells[1, 1, 1, 100]); //Cells[RowStart, ColumnStart, RowEnd, ColumnEnd ]
int colNumber = 1;
foreach (DataColumn col in ReportDtTbl.Columns)
{
if (col.DataType == typeof(DateTime))
{
ws.Column(colNumber).Style.Numberformat.Format = "dd/MM/yyyy hh:mm:ss";
//DataColumn col.ExtendedProperties.Add("TZ", +2);
}
colNumber++;
}
ws.Cells["A2"].LoadFromDataTable(ReportDtTbl, false);
// save our new workbook in the output directory and we are done!
ReportExcel = pck.GetAsByteArray();
//pck.Save();
}
return ReportExcel;
您應該更改對數據庫的查詢以考慮與 UTC 相比的本地時間差異,而不是在返回數據后更改日期時間。
SELECT CONVERT(datetime,
SWITCHOFFSET(CONVERT(datetimeoffset,
MyTable.UtcColumn),
DATENAME(TzOffset, SYSDATETIMEOFFSET())))
AS ColumnInLocalTime
FROM MyTable
如本答案所述,請勿減去小時數: Convert Datetime column from UTC to local time in select statement
因為它已經是日期時間類型:
TimeZoneInfo tz= TimeZoneInfo.FindSystemTimeZoneById("<timezone column?>");//"Central Standard Time"
DateTime tzTime = TimeZoneInfo.ConvertTimeFromUtc(<utctime>, tzTime );
使用 IsDaylightSavingTime 檢查夏令時。
如果您不知道本地時區是什么(它不存儲在一個 coumn 中),請使用 ToLocalTime 作為文字當前時區。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.