swift - How do I "combine" an un-zoned date and a time zone? -


my question similar get "time time zone" "time without time zone" , time zone name (i think). want in swift.

anyway, trying write function following signature:

func combine(_ date: date, timezone: timezone) -> date? 

what takes in date , returns "zoned" date. if date not exist in time zone, returns nil.

to avoid being xy question, here screenshot:

enter image description here

i'm asking user date , time zone , want combine these 2 1 single date.

i'll try best explain. express dates in format of timeintervalfrom1970 make clear possible.

say pass in 0 date , gmt-1 time zone, it'll return 3600. 0 1970-1-1 00:00:00. 1970-1-1 00:00:00 in gmt-1 1970-1-1 01:00:00 in gmt, 3600.

this how tried implement this:

return date.addingtimeinterval(-timezone.secondsfromgmt(for: date)) 

this seems work not of time. however, don't think returns correct results if dst gets involved , whole thing becomes messy. feels "math-ish". prefer approach without math, using foundation api methods.

so, how can implement method?

in example, api gives date, want interpret "2017/08/18 8:08" in given time zone. assuming eureka forms ui element uses timezone of current calendar display, can convert date datecomponents, , date different timezone.

func combine(_ date: date, timezone: timezone) -> date? {     var cal = calendar.current     let comp = cal.datecomponents([.era, .year, .month, .day, .hour, .minute, .second], from: date)     cal.timezone = timezone     return cal.date(from: comp) } 

nil returned if day/time combination not exist in other timezone.


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -