0

Got an excel export feature where the datetime column should be localized based on the browser location (14-Nov-2022 12:51 PM EST). Using NodaTime, I am able to localize it. However, I am not able to get the timezone abbreviation (PST, EST, CST etc..,) which needs to be appended at the end of the datetime string.

public static string ToSpecificTimeZone(this DateTimeOffset utcDateTime, int offset)
{
    var offsetTimeSpan = TimeSpan.FromMinutes(offset);
    var localizedDateTime =
        Instant.FromDateTimeOffset(new DateTimeOffset(utcDateTime.DateTime, offsetTimeSpan));
    
    var localizedDateTimeString = localizedDateTime.ToString("dd-MMM-yyyy hh:mm tt", CultureInfo.InvariantCulture);

    return localizedDateTimeString;
}
  

I used this logic to get the zone abbreviation for system default, but dont know how to get it for dynamic offsets,

var zone = DateTimeZoneProviders.Tzdb.GetSystemDefault();
var zonedDateTime = SystemClock.Instance.GetCurrentInstant().InZone(zone);
var zoneName = zonedDateTime.Zone.GetZoneInterval(zonedDateTime.ToInstant()).Name;

Any tips or directions would be really helpful.

Raajkumar
  • 857
  • 2
  • 13
  • 26
  • 2
    Not sure I've understood the question properly but I'm not sure it makes sense to do this as more than 1 timezone can (more likely does) share the same offset at any moment in time. How would you choose between them? – phuzi Nov 14 '22 at 23:20
  • hmm, is there a better approach? – Raajkumar Nov 14 '22 at 23:59
  • 2
    Yes, get the time zone id from the browser with `Intl.DateTimeFormat().resolvedOptions().timeZone` and use that with NodaTime's TZDB provider. See https://stackoverflow.com/a/34602679/634824 – Matt Johnson-Pint Nov 15 '22 at 02:28

0 Answers0