c# - TimeZoneInfo - AdjustmentRule error on .net core 1.1 -


i have piece of code allows me current date/time (local).

it run on azure.

i'm getting universal time , converting local uk time (taking consideration bst - british summer time).

while migrating .net 4.6.1/core project .net core 1.1 i'm faced error.

the type name 'adjustmentrule' not exist in type 'timezoneinfo'

'timezoneinfo' not contain definition 'getadjustmentrules' , no extension method 'getadjustmentrules' accepting first argument of type 'timezoneinfo' found (are missing using directive or assembly reference?)

using .net core 1.1 - how can resolve this?

public static datetime getlocaldatetimenow() {     datetime localdate = system.datetime.now.touniversaltime();      // venue time zone info     timezoneinfo tz = timezoneinfo.findsystemtimezonebyid("gmt standard time");     timespan timediffutcclient = tz.baseutcoffset;     localdate = system.datetime.now.touniversaltime().add(timediffutcclient);      if (tz.supportsdaylightsavingtime && tz.isdaylightsavingtime(localdate))     {         timezoneinfo.adjustmentrule[] rules = tz.getadjustmentrules();         foreach (var adjustmentrule in rules)         {             if (adjustmentrule.datestart <= localdate && adjustmentrule.dateend >= localdate)             {                 localdate = localdate.add(adjustmentrule.daylightdelta);             }         }     }      datetimeoffset utcdate = localdate.touniversaltime();      return localdate; } 

i don't mind replacing implementation long takes account bst , runs on .net core 1.1 (without 4.6.1).

you shouldn't need of - ask timezoneinfo conversion. that's it's there for!

// need once... private static readonly timezoneinfo londonzone =     timezoneinfo.findsystemtimezonebyid("gmt standard time");  public static datetime getukdatetimenow() =>     timezoneinfo.converttime(datetime.utcnow, londonzone); 

a few notes:

  • i've renamed getlocaldatetimenow() getukdatetimenow() make clear it's dealing uk time zone, not time zone local particular user or computer
  • on unix, you'd need ask "europe/london" instead of "gmt standard time"
  • to make independent of of - , indeed of system local time zone data - use noda time project i'd think give cleaner code instead.

almost no-one needs deal adjustmentrule in code. in noda time, because need able represent timezoneinfo zones noda time datetimezone objects, that's pretty unusual. if ever do need use them, they're far more complicated might expect, , there have been several occurrences of bugs in .net implementation; i'm (as in, today) fighting bugs in mono implementation instead...

as aside, strongly urge not use datetime.now anywhere. use datetime.utcnow, , convert system local time zone if really, need to.


Comments