jstedfast / MailKit

A cross-platform .NET library for IMAP, POP3, and SMTP.
http://www.mimekit.net
MIT License
6.04k stars 809 forks source link

FormatInternalDate outputs wrong formatted dates with timezones having negative offsets #1753

Closed elkoiko closed 1 month ago

elkoiko commented 1 month ago

First of all

First of all, thank you very much for your work on MailKit. I'm very pleased to have the opportunity to contribute to it ! Now, let's see what I found 😃.

Issue

The FormatInternalDate method has a bug when handling time zones with negative offsets where the minutes component was non-zero. This resulted in incorrectly formatted outputs. Specifically, the method produced an invalid format with an extra negative sign for the minutes part. Examples of the incorrect outputs included:

Expected: 14-May-2023 12:30:45 -0430
But was: 14-May-2023 12:30:45 -04-30

Expected: 15-May-2023 12:30:45 -0330
But was: 15-May-2023 12:30:45 -03-30

These incorrect outputs are associated with time zones such as:

Fix

To address this issue, I formatted the time zone offset beforehand to ensure the correct inclusion of the sign and the proper formatting of hours and minutes in an invariant culture way. Along the process, I also created unit tests that confirm that the fix does not introduce regressions.

jstedfast commented 1 month ago

I think a simpler solution is to just use Math.Abs() on the offset minutes:

return string.Format (CultureInfo.InvariantCulture, "{0:D2}-{1}-{2:D4} {3:D2}:{4:D2}:{5:D2} {6:+00;-00}{7:00}",
                date.Day, Months[date.Month - 1], date.Year, date.Hour, date.Minute, date.Second,
                date.Offset.Hours, Math.Abs (date.Offset.Minutes));

This would require fewer string allocations.

jstedfast commented 1 month ago

Awesome, thanks for the fix!