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())
How to get the current time as datetime
Update for Swift 3:
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
I do this:
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
let hour = components.hour
let minutes = components.minute
See the same question in objective-c How do I get hour and minutes from NSDate?
Compared to Nate’s answer, you’ll get numbers with this one, not strings… pick your choice!
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 the current date and time of another timezone in Swift?
There are a number of ways to get a local time, such as using string time zone identifiers and seconds from GMT. And there are a number of formats to express time, such as strings and native Date
objects. You didn't specify much in your question, so here's a starting point:
func localTime(in timeZone: String) -> String {
let f = ISO8601DateFormatter()
f.formatOptions = [.withInternetDateTime]
f.timeZone = TimeZone(identifier: timeZone)
return f.string(from: Date())
}
print(localTime(in: "Asia/Tehran")) // 2019-11-20T20:17:13+03:30 (8:17 PM)
How many time zones there are in the world is not entirely definitive but the general consensus appears to be 38. I prefer using secondsFromGMT
because it's more deterministic than using string identifiers because the string identifiers are subject to change (as this is a Swift library), while secondsFromGMT
cannot (without a change in the timezone itself).
// For a list of all time zone string identifiers
for timeZone in TimeZone.knownTimeZoneIdentifiers {
print(timeZone)
}
Unfortunately, secondsFromGMT
does not recognize fractional time zones, and there are quite a few; therefore, we can use both methods to get a complete list of 38:
-12:00 TimeZone(secondsFromGMT: -43200)
-11:00 TimeZone(secondsFromGMT: -39600)
-10:00 TimeZone(secondsFromGMT: -36000)
-09:30 TimeZone(identifier: "Pacific/Marquesas")
-09:00 TimeZone(secondsFromGMT: -32400)
-08:00 TimeZone(secondsFromGMT: -28800)
-07:00 TimeZone(secondsFromGMT: -25200)
-06:00 TimeZone(secondsFromGMT: -21600)
-05:00 TimeZone(secondsFromGMT: -18000)
-04:00 TimeZone(secondsFromGMT: -14400)
-03:30 TimeZone(identifier: "America/St_Johns")
-03:00 TimeZone(secondsFromGMT: -10800)
-02:00 TimeZone(secondsFromGMT: -7200)
-01:00 TimeZone(secondsFromGMT: -3600)
+00:00 TimeZone(secondsFromGMT: 0)
+01:00 TimeZone(secondsFromGMT: 3600)
+02:00 TimeZone(secondsFromGMT: 7200)
+03:00 TimeZone(secondsFromGMT: 10800)
+03:30 TimeZone(identifier: "Asia/Tehran")
+04:00 TimeZone(secondsFromGMT: 14400)
+04:30 TimeZone(identifier: "Asia/Kabul")
+05:00 TimeZone(secondsFromGMT: 18000)
+05:30 TimeZone(identifier: "Asia/Colombo")
+05:45 TimeZone(identifier: "Asia/Kathmandu")
+06:00 TimeZone(secondsFromGMT: 21600)
+06:30 TimeZone(identifier: "Asia/Yangon")
+07:00 TimeZone(secondsFromGMT: 25200)
+08:00 TimeZone(secondsFromGMT: 28800)
+08:45 TimeZone(identifier: "Australia/Eucla")
+09:00 TimeZone(secondsFromGMT: 32400)
+09:30 TimeZone(identifier: "Australia/Adelaide")
+10:00 TimeZone(secondsFromGMT: 36000)
+10:30 TimeZone(identifier: "Australia/Lord_Howe")
+11:00 TimeZone(secondsFromGMT: 39600)
+12:00 TimeZone(secondsFromGMT: 43200)
+12:45 TimeZone(identifier: "Pacific/Chatham")
+13:00 TimeZone(secondsFromGMT: 46800)
+14:00 TimeZone(secondsFromGMT: 50400)
iOS Swift - Get the Current Local Time and Date Timestamp
For saving Current time to firebase database I use Unic Epoch Conversation:
let timestamp = NSDate().timeIntervalSince1970
and For Decoding Unix Epoch time to Date().
let myTimeInterval = TimeInterval(timestamp)
let time = NSDate(timeIntervalSince1970: TimeInterval(myTimeInterval))
How can i get Local DateFormat with swift?
You can use :
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .short
But these won't come in the same format dd.MM.yyyy HH:mm
How to Convert date into local time zone ios swift
If you want the result to be a Date object just use the first part of @Intellij-Shivam's answer:
func serverToLocal(date:String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let localDate = dateFormatter.date(from: date)
return localDate
}
(note that DateFormatter.date(from:)
returns an optional, which is correct because the input date string might not be in the correct format.)
There is no such thing as a Date
in your local time zone. Dates
don't have a time zone. They record an instant in time all over the planet.
To display a date in your local time zone you can use the DateFormatter
class method localizedString()
:
let dateString = DateFormatter.localizedString(
inputDate,
dateStyle: .medium,
timeStyle: .medium)
Create a local date at a specific time in Swift
The answer – as already mentioned in the comments – is: print
displays Date
instances in GMT. 2018-01-26 23:00:00 +0000
is the same point in time as 2018-01-27 00:00:00 +0100
Apart from that I'd like to suggest a much more reliable way to get todayStartDate
and todayEndDate
using Calendar
's powerful date math skills.
let calendar = Calendar.current
var todayStartDate = Date()
var interval = TimeInterval()
calendar.dateInterval(of: .day, start: &todayStartDate, interval: &interval, for: Date())
let todayEndDate = calendar.date(byAdding: .second, value: Int(interval-1), to: todayStartDate)!
print(todayStartDate)
print(todayEndDate)
How can I determine the time zone of a given (local) date
The answer was quite simple - still I didn't see it for hours. The trick is to set a timeZone for the DateFormatter.
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let dateUTC = dateFormatter.date(from: current.currentObservation[0].timeUTC)!
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let dateLocal = dateFormatter.date(from: current.currentObservation[0].timeLocal)!
let difference = Calendar.current.dateComponents([.second], from: dateUTC, to: dateLocal).second!
Related Topics
How to Get Image Metadata in iOS
Color All Occurrences of String in Swift
Cocoapods: Failed to Connect to Github to Update the Cocoapods/Specs Specs Repo
How to Disable/Enable the Sleep Mode Programmatically in iOS
First App Update, User Data Lost (Was Stored in Documents Directory)
How to Set a Uitableview to Grouped Style
Xcode - Error Creating Lldb Target
Uibutton That Resizes to Fit Its Titlelabel
Error: Invalid Bitcode Version (Producer: '800.0.35.0_0' Reader: '703.0.31_0')
Creating Framework That Requires (Depends On) Another Framework
iOS 13.1 Crash in Avaudio Player
Pod Install Is Staying on "Setting Up Cocoapods Master Repo"
Ios: Uibutton Resize According to Text Length