1

我正在尝试将下面的代码从 VB6 转换为 C#。我只是不确定从哪里开始,我想可能是因为我被 VB6 深深吸引,似乎无法退后一步。

Private Function GMT_OFFSET() As Integer
    '****DECLARE VARIABLES
    Dim dtNow As Date, dtEngland As Date
    Dim dtGMT As SYSTEMTIME
    '****GET SYSTEM TIME INFORMATION
    Call GetSystemTime(dtGMT)
    dtNow = Now
    dtEngland = dtGMT.wYear & "-" & dtGMT.wMonth & "-" & dtGMT.wDay & " " & dtGMT.wHour & ":" & dtGMT.wMinute & ":" & dtGMT.wSecond
    '****RETURN QUARTER HOURS
    GMT_OFFSET = DateDiff("n", dtEngland, dtNow) \ 15
End Function

我知道 GetSystemTime 是一个 Win32 API,显然不想在 .NET 中执行 PInvoke,而是在 .NET Framework 中使用纯对象。

4

3 回答 3

2

根据您的代码,您正在寻找以下内容:

        var dtNow = DateTime.Now;
        var dtOffset = (dtNow.ToUniversalTime().Subtract(dtNow)).TotalMinutes / 15;

如果通用时间大于当前系统时间,您可能需要负向调整偏移量。

于 2012-08-02T19:04:56.190 回答
1

系统时间:

DateTime systemDateTime = DateTime.Now;

但更重要的是,系统运行的偏移量:

TimeZoneInfo systemTimeZone = TimeZoneInfo.Local;
TimeSpan offset = systemTimeZone.GetUtcOffset();
Int32 offsetMinutes = offset.Hours * 60 + offset.Minutes;
于 2012-08-02T19:22:49.843 回答
1

近直接翻译:

//Private Function GMT_OFFSET() As Integer
int GMT_OFFSET()
{
  //'****DECLARE VARIABLES
  //Dim dtNow As Date, dtEngland As Date
  DateTime dtNow, dtEngland;
  //Dim dtGMT As SYSTEMTIME
  //'****GET SYSTEM TIME INFORMATION
  //Call GetSystemTime(dtGMT)
  //dtNow = Now
  //dtEngland = dtGMT.wYear & "-" & dtGMT.wMonth & "-" & dtGMT.wDay & " " & dtGMT.wHour & ":" & dtGMT.wMinute & ":" & dtGMT.wSecond
  dtEngland = DateTime.UtcNow;
  dtNow = dtEngland.ToLocalTime;
  //'****RETURN QUARTER HOURS
  //GMT_OFFSET = DateDiff("n", dtEngland, dtNow) \ 15
  return Convert.ToInt32((dtNow - dtEngland).TotalMinutes) / 15;
//End Function
}

NB VB6 的DateDiff(interval,date1,date2)结果基于date2 - date1反之亦然

但单线是:

return Convert.ToInt32(TimeZoneInfo.Local.GetUtcOffset(DateTime.UtcNow).TotalMinutes) / 15;
于 2012-08-03T14:38:27.220 回答