I created a small app to test storing times with the UTC offset. I don't understand the results. If I run the program at 14:01 today, I get this:
This:
InsertPunch(new Employee { Id = 10, TimeZoneId = "Central Standard Time" });
Produces this in the DB:
2021-01-08 13:01:06.3594141 -05:00
This:
InsertPunch(new Employee { Id = 12, TimeZoneId = "Eastern Standard Time" });
Produces this in the DB:
2021-01-08 14:01:07.5587251 -05:00
The times are correct; the first is indeed CT and the second is indeed ET. But why is the offset -5 for both? Shouldn't the offset for CT be -6? I was assuming we could look at a time like this:
2021-01-08 14:01:07.5587251 -05:00
...and we know that UTC time is 19:01 (14:01 + 5:00). That's correct. But the results for CT are incorrect: 13:01 + 5:00 = 18:01, and the current UTC time is actually 19:01.
Am I understanding this incorrectly? Or perhaps I'm doing something wrong?
static void Main(string[] args)
{
InsertPunch(new Employee { Id = 10, TimeZoneId = "Central Standard Time" });
InsertPunch(new Employee { Id = 12, TimeZoneId = "Eastern Standard Time" });
Console.WriteLine("Press any key to end.");
Console.ReadKey();
}
private static void InsertPunch(Employee employee)
{
var punchTimeUtc = DateTime.UtcNow; // Need timestamp in UTC to properly convert to employee's time zone.
var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(employee.TimeZoneId); // Reference the employee's time zone.
var punchTimeInUsersZone = TimeZoneInfo.ConvertTimeFromUtc(punchTimeUtc, timeZoneInfo);
var punch = new Punch
{
EmployeeId = employee.Id,
PunchTime = punchTimeInUsersZone
};
string sql = "INSERT INTO [time].[Punch] ([EmployeeId],[PunchTime]) VALUES (@EmployeeId, @PunchTime)";
using (IDbConnection db = new SqlConnection(_connectionString))
{
db.Execute(sql, new { punch.EmployeeId, punch.PunchTime });
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…