Get Current iPhone Device Timezone Date and Time from Utc-5 Timezone Date and Time iPhone App

Get current iPhone device timezone date and time from UTC-5 timezone date and time iPhone app?

I have tested your scenario and added some code for your reference. Please test the below and please let me know it is useful for you.

NSString *dateStr = @"2012-07-16 07:33:01";
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [dateFormatter1 dateFromString:dateStr];
NSLog(@"date : %@",date);

NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone];
NSTimeZone *utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];

NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:date];
NSInteger gmtOffset = [utcTimeZone secondsFromGMTForDate:date];
NSTimeInterval gmtInterval = currentGMTOffset - gmtOffset;

NSDate *destinationDate = [[[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:date] autorelease];

NSDateFormatter *dateFormatters = [[NSDateFormatter alloc] init];
[dateFormatters setDateFormat:@"dd-MMM-yyyy hh:mm"];
[dateFormatters setDateStyle:NSDateFormatterShortStyle];
[dateFormatters setTimeStyle:NSDateFormatterShortStyle];
[dateFormatters setDoesRelativeDateFormatting:YES];
[dateFormatters setTimeZone:[NSTimeZone systemTimeZone]];  
dateStr = [dateFormatters stringFromDate: destinationDate];
NSLog(@"DateString : %@", dateStr);

Thanks.

How to get current date from current timezone from a time server in Swift?

If you need to make sure the date is a valid date you can use a timeserver to return the date based on the device IP, of course this will require an internet connection.

You can create a asynchronous method to return the current date regardless of the user timezone and its timezone as well:



struct Root: Codable {
let unixtime: Date
let timezone: String
}


extension URL {
static let timeIP = URL(string: "http://worldtimeapi.org/api/ip")!
static func asyncTime(completion: @escaping ((Date?, TimeZone?, Error?)-> Void)) {
URLSession.shared.dataTask(with: .timeIP) { data, response, error in
guard let data = data else {
completion(nil, nil, error)
return
}
do {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
let root = try decoder.decode(Root.self, from: data)
completion(root.unixtime, TimeZone(identifier: root.timezone), nil)
} catch {
completion(nil, nil, error)
}
}.resume()
}
}

Usage:

URL.asyncTime { date, timezone, error in
guard let date = date, let timezone = timezone else {
print("Error:", error ?? "")
return
}
print("Date:", date.description(with: .current)) // "Date: Tuesday, July 28, 2020 at 4:27:36 AM Brasilia Standard Time\n"
print("Timezone:", timezone) // "Timezone: America/Sao_Paulo (current)\n"
}

How to get store opening hours in local timezone from given date-time response? - SWIFT 5

Here is conversion of weekday and time in GMT into PST time zone:

let weekday = 2 // weekday == 1 is Sunday
let hour = 4 // 4:00 am in GMT+0
let minute = 0 // in GMT+0
guard let timeZone = TimeZone(secondsFromGMT: 0) else { return }
var calendar = Calendar(identifier: .gregorian) // Should be the calendar that is used by your server
calendar.timeZone = timeZone
let date = Date()
let dateComponents = calendar.dateComponents(Set(arrayLiteral: Calendar.Component.weekday,
Calendar.Component.hour,
Calendar.Component.minute), from: date)
var dateComponentsDiff = DateComponents()
dateComponentsDiff.day = weekday - dateComponents.weekday!
dateComponentsDiff.hour = hour - dateComponents.hour!
dateComponentsDiff.minute = minute - dateComponents.minute!
guard let arbitraryDate = calendar.date(byAdding: dateComponentsDiff, to: date),
let pstTimeZone = TimeZone(abbreviation: "PST") else { return }
let pstDateComponents = calendar.dateComponents(in: pstTimeZone, from: arbitraryDate)
print("WEEK DAY: \(pstDateComponents.weekday!)\nTIME: \(pstDateComponents.hour!):\(pstDateComponents.minute!)")

Output:

WEEK DAY: 1
TIME: 20:0

Swift - Get local date and time

I already found the answer.

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy HH:mm"
let dateInFormat = dateFormatter.stringFromDate(NSDate())

Timezone issue when date display in UI(show 1 day lesser) in Objective C

originalDateValue is always being set to UTC time for the date you are giving it. NSDate works on UTC time since you aren't specifying a timezone. dateFormatter is converting the input you're giving it to your localtime, which is several hours behind. Since you don't specify a time, it's setting the time to 00:00:00 midnight, so when converting fro UTC to Washington DC, you're adjusting the timezone several hours behind.

You must adjust the source date according to the offset from UTC to localTimeZone:

NSInteger sourceUTCOffset = [sourceTimeZone secondsFromGMTForDate:originalDateValue];
NSInteger destinationUTCOffset = [localTimeZone secondsFromGMTForDate:originalDateValue];
NSTimeInterval interval = destinationUTCOffset - sourceUTCOffset;

NSDate destinationDate = [initWithTimeInterval:interval sinceDate:originalDateValue];

Then operate on destinationDate the way you have already provided.

Objective-C, How can I get the current date in UTC timezone?

NSDate *currentDate = [[NSDate alloc] init];

Now it is in UTC, (at least after using the method below)

To store this time as UTC (since refernce date 1970) use

double secsUtc1970 = [[NSDate date]timeIntervalSince1970];

Set Date formatter to output local time:

NSTimeZone *timeZone = [NSTimeZone defaultTimeZone];
// or Timezone with specific name like
// [NSTimeZone timeZoneWithName:@"Europe/Riga"] (see link below)
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSString *localDateString = [dateFormatter stringFromDate:currentDate];

Available NSTimeZone names

A NSDate object always uses UTC as time reference, but the string representation of a date is not neccessarily based on UTC timezone.

Please note that UTC is not (only) a timeZone, It is a system how time on earth is measured, how it is coordinated (The C in UTC stands for coordinated).

The NSDate is related to a reference Date of midnight 1.1.1970 UTC, altough slightly wrongly described by Apple as 1.1.1970 GMT.

In the original question the last word timeZone is not perfect.

How to get a user's time zone?

edit/update:

Xcode 8 or later • Swift 3 or later

var secondsFromGMT: Int { return TimeZone.current.secondsFromGMT() }
secondsFromGMT // -7200

if you need the abbreviation:

var localTimeZoneAbbreviation: String { return TimeZone.current.abbreviation() ?? "" }
localTimeZoneAbbreviation // "GMT-2"

if you need the timezone identifier:

var localTimeZoneIdentifier: String { return TimeZone.current.identifier }

localTimeZoneIdentifier // "America/Sao_Paulo"

To know all timezones abbreviations available:

var timeZoneAbbreviations: [String:String] { return TimeZone.abbreviationDictionary }
timeZoneAbbreviations // ["CEST": "Europe/Paris", "WEST": "Europe/Lisbon", "CDT": "America/Chicago", "EET": "Europe/Istanbul", "BRST": "America/Sao_Paulo", "EEST": "Europe/Istanbul", "CET": "Europe/Paris", "MSD": "Europe/Moscow", "MST": "America/Denver", "KST": "Asia/Seoul", "PET": "America/Lima", "NZDT": "Pacific/Auckland", "CLT": "America/Santiago", "HST": "Pacific/Honolulu", "MDT": "America/Denver", "NZST": "Pacific/Auckland", "COT": "America/Bogota", "CST": "America/Chicago", "SGT": "Asia/Singapore", "CAT": "Africa/Harare", "BRT": "America/Sao_Paulo", "WET": "Europe/Lisbon", "IST": "Asia/Calcutta", "HKT": "Asia/Hong_Kong", "GST": "Asia/Dubai", "EDT": "America/New_York", "WIT": "Asia/Jakarta", "UTC": "UTC", "JST": "Asia/Tokyo", "IRST": "Asia/Tehran", "PHT": "Asia/Manila", "AKDT": "America/Juneau", "BST": "Europe/London", "PST": "America/Los_Angeles", "ART": "America/Argentina/Buenos_Aires", "PDT": "America/Los_Angeles", "WAT": "Africa/Lagos", "EST": "America/New_York", "BDT": "Asia/Dhaka", "CLST": "America/Santiago", "AKST": "America/Juneau", "ADT": "America/Halifax", "AST": "America/Halifax", "PKT": "Asia/Karachi", "GMT": "GMT", "ICT": "Asia/Bangkok", "MSK": "Europe/Moscow", "EAT": "Africa/Addis_Ababa"]

To know all timezones names (identifiers) available:

var timeZoneIdentifiers: [String] { return TimeZone.knownTimeZoneIdentifiers }
timeZoneIdentifiers // ["Africa/Abidjan", "Africa/Accra", "Africa/Addis_Ababa", "Africa/Algiers", "Africa/Asmara", "Africa/Bamako", "Africa/Bangui", "Africa/Banjul", "Africa/Bissau", "Africa/Blantyre", "Africa/Brazzaville", "Africa/Bujumbura", "Africa/Cairo", "Africa/Casablanca", "Africa/Ceuta", "Africa/Conakry", "Africa/Dakar", "Africa/Dar_es_Salaam", "Africa/Djibouti", "Africa/Douala", "Africa/El_Aaiun", "Africa/Freetown", "Africa/Gaborone", "Africa/Harare", "Africa/Johannesburg", "Africa/Juba", "Africa/Kampala", "Africa/Khartoum", "Africa/Kigali", "Africa/Kinshasa", "Africa/Lagos", "Africa/Libreville", "Africa/Lome", "Africa/Luanda", "Africa/Lubumbashi", "Africa/Lusaka", "Africa/Malabo", "Africa/Maputo", "Africa/Maseru", "Africa/Mbabane", "Africa/Mogadishu", "Africa/Monrovia", "Africa/Nairobi", "Africa/Ndjamena", "Africa/Niamey", "Africa/Nouakchott", "Africa/Ouagadougou", "Africa/Porto-Novo", "Africa/Sao_Tome", "Africa/Tripoli", "Africa/Tunis", "Africa/Windhoek", "America/Adak", "America/Anchorage", "America/Anguilla", "America/Antigua", "America/Araguaina", "America/Argentina/Buenos_Aires", "America/Argentina/Catamarca", "America/Argentina/Cordoba", "America/Argentina/Jujuy", "America/Argentina/La_Rioja", "America/Argentina/Mendoza", "America/Argentina/Rio_Gallegos", "America/Argentina/Salta", "America/Argentina/San_Juan", "America/Argentina/San_Luis", "America/Argentina/Tucuman", "America/Argentina/Ushuaia", "America/Aruba", "America/Asuncion", "America/Atikokan", "America/Bahia", "America/Bahia_Banderas", "America/Barbados", "America/Belem", "America/Belize", "America/Blanc-Sablon", "America/Boa_Vista", "America/Bogota", …, "Pacific/Marquesas", "Pacific/Midway", "Pacific/Nauru", "Pacific/Niue", "Pacific/Norfolk", "Pacific/Noumea", "Pacific/Pago_Pago", "Pacific/Palau", "Pacific/Pitcairn", "Pacific/Pohnpei", "Pacific/Ponape", "Pacific/Port_Moresby", "Pacific/Rarotonga", "Pacific/Saipan", "Pacific/Tahiti", "Pacific/Tarawa", "Pacific/Tongatapu", "Pacific/Truk", "Pacific/Wake", "Pacific/Wallis"]

There is a few other info you may need:

var isDaylightSavingTime: Bool { return TimeZone.current.isDaylightSavingTime(for: Date()) }
print(isDaylightSavingTime) // true (in effect)

var daylightSavingTimeOffset: TimeInterval { return TimeZone.current.daylightSavingTimeOffset() }
print(daylightSavingTimeOffset) // 3600 seconds (1 hour - daylight savings time)

var nextDaylightSavingTimeTransition: Date? { return TimeZone.current.nextDaylightSavingTimeTransition } // "Feb 18, 2017, 11:00 PM"
print(nextDaylightSavingTimeTransition?.description(with: .current) ?? "none")
nextDaylightSavingTimeTransition // "Saturday, February 18, 2017 at 11:00:00 PM Brasilia Standard Time\n"

var nextDaylightSavingTimeTransitionAfterNext: Date? {
guard
let nextDaylightSavingTimeTransition = nextDaylightSavingTimeTransition
else { return nil }
return TimeZone.current.nextDaylightSavingTimeTransition(after: nextDaylightSavingTimeTransition)
}

nextDaylightSavingTimeTransitionAfterNext // "Oct 15, 2017, 1:00 AM"

TimeZone - Apple Developer Swift Documentation



Related Topics



Leave a reply



Submit