swift - Check if local time is after midnight in another timezone -
i want check if local time after midnight in time zone.
specifically, if right @ 11 pm saturday, or 1 sunday local time, want see if start of new week in central time (after 12 sunday).
you can use calendar
's datecomponents(in: timezone, from: date)
check time , date in timezone. specific application:
// create current date, central time zone, , current calendar let = date() let centraltimezone = timezone(abbreviation: "cst")! let calendar = calendar.current let components = calendar.datecomponents(in: centraltimezone, from: now) if components.weekday == 1 { print("it sunday in central standard time.") } else { print("it not sunday in central standard time.") }
what you're doing there asking current calendar give full set of datecomponents in specified timezone. components.weekday
gives day of week int, starting 1 sunday in gregorian calendar.
if want know more if it's "tomorrow" somewhere, here's simple method:
func isittomorrow(in zone: timezone) -> bool { var calendarinzone = calendar(identifier: calendar.current.identifier) calendarinzone.timezone = timezone(abbreviation: "cst")! return calendarinzone.isdateintomorrow(date()) } if isittomorrow(in: centraltimezone) { print("it tomorrow.") } else { print("it not tomorrow.") }
isittomorrow(in: timezone)
creates new calendar of same type current calendar (presumably .gregorian
, never know) , sets timezone desired one. uses neat built-in calendar
method .isdateintomorrow()
check if current time "tomorrow" in target timezone.
there lots of other ways it, , depending on specific need there may built-in method save lot of work, it's worth reading through docs on calendar , datecomponents see what's available.
Comments
Post a Comment