Time converter "071953Z" (ZULU TO CURRENT TIME) - ios

I'm using an api that gives me the following time format:
"071953Z"
07 is the day
19 is the hours
53 are the minutes
Z is Zulu time
As you can see, there is no current month and year, i also want that to be added but i dont know how.
Could you help me to convert this to the current time? Thanks!

I think your best bet is to store the partial-datetime in a DateComponents. Then you can add a month and year to it and use Foundation's calendar API to do what you want:
extension DateComponents {
static func from(str: String) -> DateComponents? {
guard str.characters.count == 7 else {
return nil
}
var components = DateComponents()
components.timeZone = TimeZone(secondsFromGMT: 0)
components.calendar = Calendar(identifier: .gregorian)
let ranges = [0,2,4].map {
return str.index(str.startIndex, offsetBy: $0)..<str.index(str.startIndex, offsetBy: $0 + 2)
}
if let day = Int(str[ranges[0]]) {
components.day = day
} else {
return nil
}
if let hour = Int(str[ranges[1]]), hour < 24 {
components.hour = hour
} else {
return nil
}
if let minute = Int(str[ranges[2]]), minute < 60 {
components.minute = minute
} else {
return nil
}
return components
}
}
// This formatter is to convert the date to your local time. Configure to taste
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .medium
if var components = DateComponents.from(str: "071953Z") {
components.year = 2017
components.month = 4
if let date = components.date {
print(formatter.string(from: date))
} else {
print("\(components) does not make a valid date")
}
}

Related

IOS Count current streak of days

I'm making a day streak counter using UserDefaults and Core Data.
The idea is that a number will be added unto by 1 every separate day an action is performed-- this will be the streak number.
If this action wasn't performed for 24 hours, the number would reset to zero.
I have a function to set the end of the streak:
// set date time to the end of the day so the user has 24hrs to add to the streak
func changeDateTime(userDate: NSDate) -> NSDate {
let dateComponents = NSDateComponents()
let currentCalendar = NSCalendar.current
let year = Int(currentCalendar.component(NSCalendar.Unit.Year, fromDate:
userDate))
let month = Int(currentCalendar.component(NSCalendar.Unit.Month, fromDate:
userDate))
let day = Int(currentCalendar.component(NSCalendar.Unit.Day, fromDate: userDate))
dateComponents.year = year
dateComponents.month = month
dateComponents.day = day
dateComponents.hour = 23
dateComponents.minute = 59
dateComponents.second = 59
guard let returnDate = currentCalendar.dateFromComponents(dateComponents) else {
return userDate
}
return returnDate
}
It is returning the following Errors:
'NSDate' is not implicitly convertible to 'Date'; did you mean to use
'as' to explicitly convert?
Cannot convert value of type 'NSCalendar.Unit' to expected argument
type 'Calendar.Component'
When using the suggested corrections I only get more errors with no suggested corrections. I'm having trouble figuring out the proper way to express this
The full Code is:
let userDefaults = UserDefaults.standard
var moc: NSManagedObjectContext!
var lastStreakEndDate: NSDate!
var streakTotal: Int!
override func viewDidLoad() {
super.viewDidLoad()
// checks for object if nil creates one (used for first run)
if userDefaults.object(forKey: "lastStreakEndDate") == nil {
userDefaults.set(NSDate(), forKey: "lastStreakEndDate")
}
lastStreakEndDate = (userDefaults.object(forKey: "lastStreakEndDate") as! NSDate)
streakTotal = calculateStreak(lastDate: lastStreakEndDate)
}
// fetches dates since last streak
func fetchLatestDates(moc: NSManagedObjectContext, lastDate: NSDate) -> [NSDate] {
var dates = [NSDate]()
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "streakCount")
let datePredicate = NSPredicate(format: "date < %#", lastDate)
fetchRequest.predicate = datePredicate
do {
let result = try moc.fetch(fetchRequest)
let allDates = result as! [NSDate]
if allDates.count > 0 {
for date in allDates {
dates.append(date)
}
}
} catch {
fatalError()
}
return dates
}
// set date time to the end of the day so the user has 24hrs to add to the streak
func changeDateTime(userDate: NSDate) -> NSDate {
let dateComponents = NSDateComponents()
let currentCalendar = NSCalendar.current
let year = Int(currentCalendar.component(NSCalendar.Unit.Year, fromDate: userDate))
let month = Int(currentCalendar.component(NSCalendar.Unit.Month, fromDate: userDate))
let day = Int(currentCalendar.component(NSCalendar.Unit.Day, fromDate: userDate))
dateComponents.year = year
dateComponents.month = month
dateComponents.day = day
dateComponents.hour = 23
dateComponents.minute = 59
dateComponents.second = 59
guard let returnDate = currentCalendar.dateFromComponents(dateComponents) else {
return userDate
}
return returnDate
}
// adds a day to the date
func addDay(today: NSDate) -> NSDate {
let tomorrow = NSCalendar.currentCalendar.dateByAddingUnit(.Day, value: 1, toDate: today, options: NSCalendar.Options(rawValue: 0))
return tomorrow!
}
// this method returns the total of the streak and sets the ending date of the last streak
func calculateStreak(lastDate: NSDate) -> Int {
let dateList = fetchLatestDates(moc: moc, lastDate: lastDate)
let compareDate = changeDateTime(userDate: lastDate)
var streakDateList = [NSDate]()
var tomorrow = addDay(today: compareDate)
for date in dateList {
changeDateTime(userDate: date)
if date == tomorrow {
streakDateList.append(date)
}
tomorrow = addDay(today: tomorrow)
}
userDefaults.set(streakDateList.last, forKey: "lastStreakEndDate")
return streakDateList.count
}
Any Help is Appreciated
You need
// set date time to the end of the day so the user has 24hrs to add to the streak
func changeDateTime(userDate: Date) -> Date {
var dateComponents = DateComponents()
let currentCalendar = Calendar.current
let year = Int(currentCalendar.component(.year, from:
userDate))
let month = Int(currentCalendar.component(.month, from:
userDate))
let day = Int(currentCalendar.component(.day, from: userDate))
dateComponents.year = year
dateComponents.month = month
dateComponents.day = day
dateComponents.hour = 23
dateComponents.minute = 59
dateComponents.second = 59
guard let returnDate = currentCalendar.date(from:dateComponents) else {
return userDate
}
return returnDate
}
OR shortly
// set date time to the end of the day so the user has 24hrs to add to the streak
func changeDateTime(userDate: Date) -> Date {
var dateComponents = DateComponents()
let currentCalendar = Calendar.current
let res = currentCalendar.dateComponents([.year,.month,.day],from:userDate)
dateComponents.year = res.year
dateComponents.month = res.month
dateComponents.day = res.day
dateComponents.hour = 23
dateComponents.minute = 59
dateComponents.second = 59
guard let returnDate = currentCalendar.date(from:dateComponents) else {
return userDate
}
return returnDate
}

How to compare two date components

I'm working on app like social media app where user post something on wall post data saved to server and return to app I want to get time of post like facebook Instagram etc.(5 hours ago)
the response I get from server is
"2020-03-07T13:15:09"
so first I split miliseconds from my datetime
func date(post: mdlSocialFeedbackView.mdlMemberWallPost) -> String{
let timeDateWithoutMilliseconds = post.CreatedDate!.split(separator: ".")[0]
let date = timeDateWithoutMilliseconds.split(separator: "T")[0]
let time = timeDateWithoutMilliseconds.split(separator: "T")[1]
let formatter = DateFormatter()
let timeDateObject = formatter.timeFromServer(time: String(time))
let dateObject = formatter.dateFromServer(date: String(date))
let calender = Calendar.current
let dateString = calender.dateOfPostOnWall(dateTime: dateObject!)
if let date = dateString{
return date
}else{
let timeString = calender.timeOfPostOnWall(dateTime: timeDateObject!)
return timeString!
}
}
I'm using this function in my UIViewController class to get time from server and return the exact time of post.
Extentions in Calender and DateFormatter classes and also Help me and guide me to format the current time zone
extension DateFormatter{
func dateFromServer(date: String) -> Date?{
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
//formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.timeZone = .current
return formatter.date(from: date)
}
func timeFromServer(time: String) -> Date?{
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm:ss"
//formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.timeZone = .current
return formatter.date(from: time)
}
}
extension Calendar{
func timeOfPostOnWall(dateTime: Date?)-> String?{
let componentOfTime = self.dateComponents([.hour, .minute, .second], from: dateTime!)
let componentOfCurrentTime = self.dateComponents([.hour, .minute,.second], from: Date())
guard componentOfCurrentTime.hour == componentOfTime.hour
else{
return "about \(componentOfCurrentTime.hour! - componentOfTime.hour!) hours ago."}
guard componentOfCurrentTime.minute == componentOfTime.minute
else{
return "about \(componentOfCurrentTime.minute! - componentOfTime.minute!) minutes ago."
}
guard componentOfCurrentTime.second == componentOfTime.second
else{
return "about \(componentOfCurrentTime.second! - componentOfTime.second!) seconds ago."
}
return nil
}
func dateOfPostOnWall(dateTime: Date?)-> String?{
let componentOfTime = self.dateComponents([.year, .month, .day], from: dateTime!)
let componentOfCurrentTime = self.dateComponents([.year, .month, .day], from: Date())
guard componentOfCurrentTime.year == componentOfTime.year
else{
return "about \(componentOfCurrentTime.year! - componentOfTime.year!) years ago."}
guard componentOfCurrentTime.month == componentOfTime.month
else{
return "about \(componentOfCurrentTime.month! - componentOfTime.month!) months ago."
}
guard componentOfCurrentTime.day == componentOfTime.day
else{
return "about \(componentOfCurrentTime.day! - componentOfTime.day!) days ago."
}
return nil
}
}
now the issue is when ever I post something components of current time return
enter image description here
and response on wall something like this
enter image description here
The cause of this bug seems to be that your server clock is out of sync with the device's time. You should find out which clock has the "correct" time and adjust the other clock. Alternatively, rewrite the server side code to respond with the current time according to the server's clock.
Anyway, you are also reinventing the wheel a lot in your code. The bug could also be caused by the date-and-time handling code you've written yourself. You should instead use the built-in APIs, because they are less likely to have bugs.
The date you receive is in ISO 8601 format, so you can parse it with a ISO8601DateFormatter. Your dateFromServer and timeFromServer methods are quite redundant.
func date(post: mdlSocialFeedbackView.mdlMemberWallPost) -> String{
let dateString = post.CreatedDate!
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withColonSeparatorInTime, .withTime, .withFullDate]
let date = formatter.date(from: dateString)
// to be continued
}
Your way of finding the difference between two dates is questionable to say the least. If I post something on December 31, and I view it on January 1, I would see "about 1 year ago", where I personally would expect "about 1 day ago", or less.
You can use the dateComponents(_:from:to:) method:
// Calendar extension
func estimatedTimeFromNow(date: Date)-> String {
let diff = self.dateComponents([.year, .month, day, .hour, .minute, .second], from: date, to: Date())
if let year = diff.year {
return "about \(year) year(s) ago"
} else if let month = diff.month {
return "about \(month) month(s) ago"
} else if let day = diff.day {
return "about \(day) day(s) ago"
} else if let hour = diff.hour {
return "about \(hour) hour(s) ago"
} else if let minute = diff.minute {
return "about \(minute) minute(s) ago"
} else if let second = diff.second {
return "about \(second) second(s) ago"
} else {
return "just now"
}
}
And in date(post:):
return Calendar.current.estimatedTimeFromNow(date: date)
Your date is in ISO 8601. So use an ISO8601DateFormatter!
final class ISO8601DateFormatter: Foundation.ISO8601DateFormatter {
override init() {
super.init()
formatOptions.remove(.withTimeZone)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
}
ISO8601DateFormatter().date(from: "2020-03-07T13:15:09")

Results of sorting an array are unexpected

I have a an array of objects that contains a date value. I have calculated the date differences and returned the number of days left. Now I am trying to sort it so it appends based on the object with least number of days left.
I have been able to use this function:
func sortList() {
item.sort { (first: Item, second: Item) -> Bool in
return first.days() < second.days()
}
}
Which gives me this:
However as you can see the date which is equal to 0 is appended at the bottom.
This is how I am calculating the days difference:
func daysDiff(startDate: Date, endDate: Date) -> Int {
let calendar = Calendar.current
let date1 = calendar.startOfDay(for: startDate)
let date2 = calendar.startOfDay(for: endDate)
let a = calendar.dateComponents([.day], from: date1, to: date2)
return a.value(for: .day)!
}
And this is how I am formatting it:
func days() -> String {
let formatter = DateFormatter()
formatter.dateFormat = "MM dd, yyyy"
let date = formatter.date(from: itemDate!)
let date1 = Date()
let date2 = date
let days = daysDiff(startDate: date1, endDate: date2!)
if days > 1 {
return "\(days) days left"
} else if days == 1 {
return "a day left"
} else if days == 0 {
return "Due today!"
} else if days < 0 {
return "Late"
} else {
return "\(days)"
}
}
I am not really sure why this issue is happening.
Your sort is based on the text from your days() function so you are sorting the data alphabetically based on your text. You should sort based on an actual integer value, not a string.
You should have two methods on your class.
days() which returns an Int instead of a String.
daysLabel which returns a String based on the result of days.
Use days when sorting by number. Use daysLabel when displaying an Item instance somewhere.
func days() -> Int {
let formatter = DateFormatter()
formatter.dateFormat = "MM dd, yyyy"
let date = formatter.date(from: itemDate!)
let date1 = Date()
let date2 = date
let days = daysDiff(startDate: date1, endDate: date2!)
return days
}
func daysLabel() -> String {
let days = days()
if days > 1 {
return "\(days) days left"
} else if days == 1 {
return "a day left"
} else if days == 0 {
return "Due today!"
} else if days < 0 {
return "Late"
} else {
return "\(days)"
}
}

How to get the weekday string representation for a date Swift

I'm trying to get the weekday of a date (Wednesday, Tuesday) but I can't seem to find a good way to actually get the string. This is what I'm doing:
internal func fromToday(daysAgo: Date) -> String {
let calendar = NSCalendar.autoupdatingCurrent
let startOfNow = calendar.startOfDay(for: Date())
let startOfTimeStamp = calendar.startOfDay(for: daysAgo)
let numDaysDifference = abs(calendar.dateComponents([.day], from: startOfNow, to: startOfTimeStamp).day!)
let daysAgoComponents = calendar.dateComponents([.weekday, .hour, .minute], from: daysAgo)
var hour = daysAgoComponents.hour!
var timeOfDay = "AM"
if hour >= 13 {
hour -= 12
timeOfDay = "PM"
}
var res = "\(hour):\(daysAgoComponents.minute!)\(timeOfDay)"
if calendar.isDateInYesterday(daysAgo) {
res = "Yesterday"
} else if numDaysDifference < 8 && numDaysDifference > 1 {
res = stringFromWeekday(day: daysAgoComponents.weekday!) // HERE THIS IS WHAT IM ASKING ABOUT IGNORE OTHER IFS
} else if numDaysDifference >= 8 {
res = stringFromDate(day: daysAgo)
}
return res
}
fileprivate func stringFromWeekday(day: Int) -> String {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US")
if formatter.weekdaySymbols.count < day {
print("ConversationTVC - \(day) is not a valid day of the week")
}
return formatter.weekdaySymbols[day]
}
Specifically, the line:
else if numDaysDifference < 8 && numDaysDifference > 1
res = stringFromWeekday(day: daysAgoComponents.weekday!)`
I think the issue has to do with weekdaySymbols
How do I get the string representation of the day of the week X days ago given a Date?
Issue was I wasn't subtracting 1 from day, weekday returns 1-7 and weekday symbols is 0-6

Swift convert unix time to date and time

My current code:
if let var timeResult = (jsonResult["dt"] as? Double) {
timeResult = NSDate().timeIntervalSince1970
println(timeResult)
println(NSDate())
}
The results:
println(timeResult) = 1415639000.67457
println(NSDate()) = 2014-11-10 17:03:20 +0000 was just to test to see what NSDate was providing.
I want the first to look like the last. The value for dt = 1415637900.
Also, how can I adjust to time zone? Running on iOS.
You can get a date with that value by using the NSDate(withTimeIntervalSince1970:) initializer:
let date = NSDate(timeIntervalSince1970: 1415637900)
To get the date to show as the current time zone I used the following.
if let timeResult = (jsonResult["dt"] as? Double) {
let date = NSDate(timeIntervalSince1970: timeResult)
let dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = NSDateFormatterStyle.MediumStyle //Set time style
dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle //Set date style
dateFormatter.timeZone = NSTimeZone()
let localDate = dateFormatter.stringFromDate(date)
}
Swift 3.0 Version
if let timeResult = (jsonResult["dt"] as? Double) {
let date = Date(timeIntervalSince1970: timeResult)
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = DateFormatter.Style.medium //Set time style
dateFormatter.dateStyle = DateFormatter.Style.medium //Set date style
dateFormatter.timeZone = self.timeZone
let localDate = dateFormatter.string(from: date)
}
Swift 5
if let timeResult = (jsonResult["dt"] as? Double) {
let date = Date(timeIntervalSince1970: timeResult)
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = DateFormatter.Style.medium //Set time style
dateFormatter.dateStyle = DateFormatter.Style.medium //Set date style
dateFormatter.timeZone = .current
let localDate = dateFormatter.string(from: date)
}
It's simple to convert the Unix timestamp into the desired format. Lets suppose _ts is the Unix timestamp in long
let date = NSDate(timeIntervalSince1970: _ts)
let dayTimePeriodFormatter = NSDateFormatter()
dayTimePeriodFormatter.dateFormat = "MMM dd YYYY hh:mm a"
let dateString = dayTimePeriodFormatter.stringFromDate(date)
print( " _ts value is \(_ts)")
print( " _ts value is \(dateString)")
For managing dates in Swift 3 I ended up with this helper function:
extension Double {
func getDateStringFromUTC() -> String {
let date = Date(timeIntervalSince1970: self)
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US")
dateFormatter.dateStyle = .medium
return dateFormatter.string(from: date)
}
}
This way it easy to use whenever you need it - in my case it was converting a string:
("1481721300" as! Double).getDateStringFromUTC() // "Dec 14, 2016"
Reference the DateFormatter docs for more details on formatting (Note that some of the examples are out of date)
I found this article to be very helpful as well
Here is a working Swift 3 solution from one of my apps.
/**
*
* Convert unix time to human readable time. Return empty string if unixtime
* argument is 0. Note that EMPTY_STRING = ""
*
* #param unixdate the time in unix format, e.g. 1482505225
* #param timezone the user's time zone, e.g. EST, PST
* #return the date and time converted into human readable String format
*
**/
private func getDate(unixdate: Int, timezone: String) -> String {
if unixdate == 0 {return EMPTY_STRING}
let date = NSDate(timeIntervalSince1970: TimeInterval(unixdate))
let dayTimePeriodFormatter = DateFormatter()
dayTimePeriodFormatter.dateFormat = "MMM dd YYYY hh:mm a"
dayTimePeriodFormatter.timeZone = NSTimeZone(name: timezone) as TimeZone!
let dateString = dayTimePeriodFormatter.string(from: date as Date)
return "Updated: \(dateString)"
}
func timeStringFromUnixTime(unixTime: Double) -> String {
let date = NSDate(timeIntervalSince1970: unixTime)
// Returns date formatted as 12 hour time.
dateFormatter.dateFormat = "hh:mm a"
return dateFormatter.stringFromDate(date)
}
func dayStringFromTime(unixTime: Double) -> String {
let date = NSDate(timeIntervalSince1970: unixTime)
dateFormatter.locale = NSLocale(localeIdentifier: NSLocale.currentLocale().localeIdentifier)
dateFormatter.dateFormat = "EEEE"
return dateFormatter.stringFromDate(date)
}
In Swift 5
Using this implementation you just have to give epoch time as a parameter and you will the output as (1 second ago, 2 minutes ago, and so on).
func setTimestamp(epochTime: String) -> String {
let currentDate = Date()
let epochDate = Date(timeIntervalSince1970: TimeInterval(epochTime) as! TimeInterval)
let calendar = Calendar.current
let currentDay = calendar.component(.day, from: currentDate)
let currentHour = calendar.component(.hour, from: currentDate)
let currentMinutes = calendar.component(.minute, from: currentDate)
let currentSeconds = calendar.component(.second, from: currentDate)
let epochDay = calendar.component(.day, from: epochDate)
let epochMonth = calendar.component(.month, from: epochDate)
let epochYear = calendar.component(.year, from: epochDate)
let epochHour = calendar.component(.hour, from: epochDate)
let epochMinutes = calendar.component(.minute, from: epochDate)
let epochSeconds = calendar.component(.second, from: epochDate)
if (currentDay - epochDay < 30) {
if (currentDay == epochDay) {
if (currentHour - epochHour == 0) {
if (currentMinutes - epochMinutes == 0) {
if (currentSeconds - epochSeconds <= 1) {
return String(currentSeconds - epochSeconds) + " second ago"
} else {
return String(currentSeconds - epochSeconds) + " seconds ago"
}
} else if (currentMinutes - epochMinutes <= 1) {
return String(currentMinutes - epochMinutes) + " minute ago"
} else {
return String(currentMinutes - epochMinutes) + " minutes ago"
}
} else if (currentHour - epochHour <= 1) {
return String(currentHour - epochHour) + " hour ago"
} else {
return String(currentHour - epochHour) + " hours ago"
}
} else if (currentDay - epochDay <= 1) {
return String(currentDay - epochDay) + " day ago"
} else {
return String(currentDay - epochDay) + " days ago"
}
} else {
return String(epochDay) + " " + getMonthNameFromInt(month: epochMonth) + " " + String(epochYear)
}
}
func getMonthNameFromInt(month: Int) -> String {
switch month {
case 1:
return "Jan"
case 2:
return "Feb"
case 3:
return "Mar"
case 4:
return "Apr"
case 5:
return "May"
case 6:
return "Jun"
case 7:
return "Jul"
case 8:
return "Aug"
case 9:
return "Sept"
case 10:
return "Oct"
case 11:
return "Nov"
case 12:
return "Dec"
default:
return ""
}
}
How to call?
setTimestamp(epochTime: time) and you'll get the desired output as a string.
Convert timestamp into Date object.
If timestamp object is invalid then return current date.
class func toDate(_ timestamp: Any?) -> Date? {
if let any = timestamp {
if let str = any as? NSString {
return Date(timeIntervalSince1970: str.doubleValue)
} else if let str = any as? NSNumber {
return Date(timeIntervalSince1970: str.doubleValue)
}
}
return nil
}
Swift:
extension Double {
func getDateStringFromUnixTime(dateStyle: DateFormatter.Style, timeStyle: DateFormatter.Style) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = dateStyle
dateFormatter.timeStyle = timeStyle
return dateFormatter.string(from: Date(timeIntervalSince1970: self))
}
}
Anyway #Nate Cook's answer is accepted but I would like to improve it with better date format.
with Swift 2.2, I can get desired formatted date
//TimeStamp
let timeInterval = 1415639000.67457
print("time interval is \(timeInterval)")
//Convert to Date
let date = NSDate(timeIntervalSince1970: timeInterval)
//Date formatting
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd, MMMM yyyy HH:mm:a"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let dateString = dateFormatter.stringFromDate(date)
print("formatted date is = \(dateString)")
the result is
time interval is 1415639000.67457
formatted date is = 10, November 2014 17:03:PM
If you are maximizing the Codable protocol for parsing your JSON data. You could simply make the data type of dt as Date and do:
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
For me: Converting timestamps coming from API to a valid date :
`let date = NSDate.init(fromUnixTimestampNumber: timesTamp /* i.e 1547398524000 */) as Date?`
By using this code you will be able to convert timeStamp to Time and Date
let timeStamp = Date().timeIntervalSince1970
let date = NSDate(timeIntervalSince1970: timeStamp)
let dayTimePeriodFormatter = DateFormatter()
dayTimePeriodFormatter.dateFormat = "dd MMMM,YYYY.hh:mm a"
let dateTimeString = dayTimePeriodFormatter.string(from: date as Date)
let dateTime = dateTimeString.split(separator: ".")
print( "Date = \(dateTime[0])")
print( "Time = \(dateTime[1])")
Output:
Date = 19 January,2022
Time = 10:46 AM

Resources