Convert Unix (Epoch) time to local time - ios

The API I'm using returns time as Unix time (1424952512) So far I can convert the unix time to NSDate using
func timeStamp(unixTime: Double)-> NSDate {
let interval:NSTimeInterval = unixTime
let date:NSDate = NSDate(timeIntervalSince1970: interval)
print(date)
//now date
let nowDate = NSDate()
print(nowDate)
return date
}
Now how can I compare date with nowDate and print the difference in hours or minutes?

For example with NSDateComponentsFormatter
let formatter = NSDateComponentsFormatter()
formatter.allowedUnits = [.Hour, .Minute]
formatter.unitsStyle = .Short
if let difference = formatter.stringFromDate(date, toDate: nowDate) {
print(difference)
} else {
print("invalid difference")
}

Related

Swift: Convert Dates to elapsed and remaining time string

I have a Current, Start Date, and End Date. How can I convert these dates to elapsed and remaining time format using Swift?
The format needed is 00:00:00 (hours: minutes: seconds)
Currently, I get elapsed and remaining strings using the below code.
The code returns incorrectly to the Time I see in the Simulator.
Example: If the simulator time changes to 2:45 pm
My elapsed time's second is ahead (10s) of the actual seconds shown.
And the remaining seconds shows ahead for (9s)
I am getting like this
elapsed = 01:30:10, rem = 12:30:09
Can you help me fix the code or a simpler way to get the format I want correctly?
Code:
{
let currDate = Date();
let startDate = currDate;
let endDate: Date = startDate.addingTimeInterval(TimeInterval(minutes * 60));
Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(callback), userInfo: nil, repeats: true);
}
#objc func Callback() {
let time = dateToTimerString(currDate: currDate, startDate: startDate, endDate: endDate );
NSLog( "Elapsed %#, Rem %#", time.elapsed, time.remaining );
}
func dateToTimerString(currDate: Date, startDate: Date, endDate: Date) -> (elapsed: String, remaining: String) {
let elapsedTime: TimeInterval = currDate.timeIntervalSince(startDate);
let remainingTime: TimeInterval = endDate.timeIntervalSince(currDate);
let elapsedString = format(duration: elapsedTime);
let remainingString = format(duration: remainingTime);
return (elapsedString, remainingString);
}
func format(duration: TimeInterval) -> String {
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute, .second]
formatter.unitsStyle = .positional
formatter.zeroFormattingBehavior = .pad
return formatter.string(from: duration)!
}
There is an API for that: DateComponentsFormatter
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .positional
formatter.allowedUnits = [.hour, .minute, .second]
formatter.zeroFormattingBehavior = .pad
let elapsedString = formatter.string(from: elapsedTime)
let remainingString = formatter.string(from: remainingTime)
It actually works with the exact date and time that you are creating with that current date constant. And if you are changing string to date from dateformatter then you need to check if you are getting the exact value there after changing.

Compare time duration values in Swift

I have to compare the time duration of the recorded audio file against a fixed time duration value of 10 mins (10:00). The duration of the audio file is a string.
Doing string comparison works fine if the format of recorded files duration and the format of the fixed duration is same i.e mm:ss. If the audio file has duration of format hh:mm:ss , it gives false values in certain cases.
Is there any way to handle this?
You can use this String Extension to calculate total minutes from string
extension String {
func getTimeInSeconds()-> Int? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "mm:ss" //Your date format
dateFormatter.timeZone = TimeZone.current //Current time zone
var date = Date()
if let getDate = dateFormatter.date(from: self) {//according to date format your date string
date = getDate //Convert String to Date
} else {
dateFormatter.dateFormat = "hh:mm:ss"
if let getDate = dateFormatter.date(from: self) {//according to date format your date string
date = getDate //Convert String to Date
} else {
return nil
}
}
let calendar = Calendar.current
let components = calendar.dateComponents([.hour, .minute,.second], from: date)
let hour = components.hour ?? 0
let minute = components.minute ?? 0
let seconds = components.second ?? 0
return (hour * 360) + minute*60 + seconds
}
}
You can use this extension like this
let getSeconds = "01:20".getTimeInSeconds()
it will cover both formats mm:ss and hh:mm:ss and return seconds ... you can use these seconds to compare instead of string

How do i convert Date to TimeInterval so I can use the if statements

This is my code:
if let date = messages?.date{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm a"
//let elapseTimeInSeconds = NSDate.timeIntervalSince(date)
let elapseTimeInSeconds = Date(timeIntervalSinceNow: (date as? Date))
let secondsInDays: TimeInterval = 60 * 60 * 24
if elapseTimeInSeconds > secondsInDays {
dateFormatter.dateFormat = "EEE"
} else if elapseTimeInSeconds > 7 * secondsInDays {
dateFormatter.dateFormat = "MM/dd/yy"
}
timeLabel.text = dateFormatter.string(from: date as Date)
}
this is the error:
Cannot convert value of type 'Date?' to expected argument type
'TimeInterval' (aka 'Double')
the error is on this line:
let elapseTimeInSeconds = Date(timeIntervalSinceNow: (date as? Date))
I've tried what I know and nothing has worked. Please help.
You can directly access it through property timeIntervalSinceNow of Date also there is no need to use NSDate in Swift 3 use directly Date and date(from:) method of DateFormatter return instance of Date? not NSDate?.
let timeInterval = date.timeIntervalSinceNow
And you can get TimeInterval between two dates using method timeIntervalSince(_:).
let timeInterval = date1.timeIntervalSince(date2)
Swift 3.0
You Need write code this:
let elapseTimeInSeconds = Date().timeIntervalSince(date as Date)
Strong!!! Date() or NSDate().timeIntervalSince(date as Date)

How to calculate how much time passed from the date with timezone?

I get from the server a date with this format:
2016-05-27 17:33:43+0400
Now, I want to detect, how much time passed since that date? For example 1 day 5 hours 10 minutes 20 seconds.
How can I do it? I know how to calculate this from the timestamp, but do not know how to convert this to a timestamp.
Can anyone help me with it?
For example:
Convert this 2016-05-27 17:33:43+0400 to 1464370423 this
Or maybe there are another solution. I just want to calculate how much time passed since that time
You can use NSDateComponents formatter to get the relative time between two dates. Regarding the date string format you need to use xx for the time zone part.
let dateStr = "2016-05-27 17:33:43+0400"
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ssxx"
formatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
if let date = formatter.dateFromString(dateStr) {
print(date) // "2016-05-27 13:33:00 +0000\n" -4hs
let dateComponentsFormatter = NSDateComponentsFormatter()
dateComponentsFormatter.allowedUnits = [.Day,.Hour,.Minute,.Second]
dateComponentsFormatter.unitsStyle = .Full
print(dateComponentsFormatter.stringFromDate(date, toDate: NSDate()) ?? "") // 6 days, 17 hours, 51 minutes, 29 seconds
}
given the input string you can convert it to a date and subsequently to an NSTimeInterval since the current time using the following.
let inputDate = "2016-05-27 17:33:43+0400"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ssZZZZZ"
if let aDate = dateFormatter.dateFromString(inputDate) {
let timeInterval = aDate.timeIntervalSinceNow
let dateComponentsFormatter = NSDateComponentsFormatter()
if let dateString = dateComponentsFormatter.stringFromTimeInterval(abs(timeInterval)) {
print ("Elapsed time=\(dateString)")
}
}
Output:
Elapsed time=6d 17:51:52
You can get the date as the timestamp in your question using aDate.timeIntervalSince1970
I suggest that this could help you: How to get the current time as datetime
You can get the current time and calculate the difference using the server time and your current time.
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
let hour = components.hour
let minutes = components.minute
Hope it helps.
This will tell you
"how many time"
passed since an event.
let date = Date()
let howManyTimePassed = date.timeIntervalSinceNow
TimeInterval is a typealias for a double, meaning its another way to say double. The value of the timeInterval represents seconds.
Try this class in Swift 5.1:
open class MyDateClass: NSObject {
private var result:MyDateTime!
init(dateStr: String, inputFormat: String) {
let formatter = DateFormatter()
formatter.dateFormat = inputFormat //"yyyy-MM-dd HH:mm:ss"
formatter.calendar = Calendar(identifier: .gregorian)
formatter.locale = Locale(identifier: "en_US_POSIX")
if let date = formatter.date(from: dateStr) {
let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.allowedUnits = [.year,.month,.day,.hour,.minute,.second]
dateComponentsFormatter.unitsStyle = .full
let strFromat = dateComponentsFormatter.string(from: date, to: Date()) ?? ""
var trimmedString = strFromat.replacingOccurrences(of: " ", with: "")
trimmedString = trimmedString.replacingOccurrences(of: "years", with: "")
trimmedString = trimmedString.replacingOccurrences(of: "months", with: "")
trimmedString = trimmedString.replacingOccurrences(of: "days", with: "")
trimmedString = trimmedString.replacingOccurrences(of: "hours", with: "")
trimmedString = trimmedString.replacingOccurrences(of: "minutes", with: "")
trimmedString = trimmedString.replacingOccurrences(of: "seconds", with: "")
let arr = trimmedString.split(separator: ",")
let result = MyDateTime(year: Int(arr[0]), month: Int(arr[1]), day: Int(arr[2]), hour: Int(arr[3]), minute: Int(arr[4]), second: Int(arr[5]))
self.result = result
}
}
func getDateTime() -> MyDateTime {
return result
}
}
public struct MyDateTime {
var year:Int?
var month:Int?
var day:Int?
var hour:Int?
var minute:Int?
var second:Int?
}
And this class works like this:
let myClass = MyDateClass(dateStr: "2016-05-27 17:33:43", inputFormat: "yyyy-MM-dd HH:mm:ss")
let time = myClass.getDateTime()
Now you can show time as you wish.

How can I convert the 24 hour time format to 12 hour time format?

I can get the 24 hour style time, but how do I get the 12 hour format with the am and pm?
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Hour, .Minute, .Second], fromDate: date)
let hour = components.hour
let minutes = components.minute
As you say, you should use NSDateFormatter for your desired format. Hope this will help you.
let date = NSDate()
let formatter = NSDateFormatter()
formatter.dateFormat = "hh:mm a"
let time = formatter.stringFromDate(date)
For more information about date formatter see NSDateFormatter
Swift 3.1 Answer
let date = Date() //Jun 1, 2017, 10:22 AM"
let formatter = DateFormatter() //<NSDateFormatter: 0x608000244380>
formatter.dateFormat = "hh:mm a" //<NSDateFormatter: 0x608000244380>
let time = formatter.string(from: date) //"10:22 AM"
Time format must be in 'hh' not HH
formatter.dateFormat = "hh:mm a"
let str=dict["startDateTime"] as! String //if the date is in the array
let str="16:00" //if you want to use static date
let index=str.index(str.startIndex, offsetBy: 11)
let end_index=str.index(str.endIndex, offsetBy:-3)
let dateAsString = str[index ..< end_index]
let dateFormatter=DateFormatter()
dateFormatter.dateFormat="HH:mm"
let date = dateFormatter.date(from: String(dateAsString))
dateFormatter.dateFormat = "h:mm a"
let Date12 = dateFormatter.string(from: date!)
print(Date12)

Resources