1

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?

Ashok
  • 5,585
  • 5
  • 52
  • 80
  • If you have simplistic string as "13 December 2017" to convert to date, what is the place for timezone? – Hexfire Dec 11 '17 at 07:47
  • @Hexfire I need to generate epoch timestamp for that date string in that time zone irrespective of device's local timezone and send it to the server. – Ashok Dec 11 '17 at 07:55
  • 1
    okay, I think below you have a good solution – Hexfire Dec 11 '17 at 07:56

1 Answers1

3

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
Ashok
  • 5,585
  • 5
  • 52
  • 80
mugx
  • 9,869
  • 3
  • 43
  • 55