Search code examples
iosswiftnsdatensdateformatternsdatecomponents

Converting date string with timezone to seconds in swift


I have a date string: "13 December 2017"

a time zone string: "Asia/Kolkata"

What is the way to get Epoch timestamp in seconds in Swift 4.0?


Solution

  • here the solution:

    // your input
    let dateStr = "13 December 2017"
    let timeZoneStr = "Asia/Kolkata"
    
    // building the formatter
    let formatter = DateFormatter()
    formatter.dateFormat = "d MMMM yyyy"
    formatter.timeZone = TimeZone(identifier: timeZoneStr)
    
    // extracting the epoch
    let date = formatter.date(from: dateStr) // Dec 13, 2017 at 3:30 AM
    let epoch = date?.timeIntervalSince1970
    print(epoch ?? "") // 1513103400
    

    for information, this link: http://userguide.icu-project.org/formatparse/datetime is an interesting source of date formatters


    Updated:

    Using Extension:

    extension String {
    
      func epoch(dateFormat: String = "d MMMM yyyy", timeZone: String? = nil) -> TimeInterval? {
        // building the formatter
        let formatter = DateFormatter()
        formatter.dateFormat = dateFormat
        if let timeZone = timeZone { formatter.timeZone = TimeZone(identifier: timeZone) }
    
        // extracting the epoch
        let date = formatter.date(from: self)
        return date?.timeIntervalSince1970
      }
    
    }
    
    "13 December 2017".epoch(timeZone: "Asia/Kolkata") // 1513103400