I am getting two date string in this format, "08:00:00" coming from server side as a starting slot or ending slot. I have to get the time of local timezone and then check if the current time lies in between the time interval which is coming from server.
But I am unable to do the comparison.
func checkTime() -> Bool {
let dateFormatter: DateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
dateFormatter.timeZone = TimeZone(identifier: "PKT")
let startingSlot = self.selectedArea.startingSlot! //UTC
let endingSlot = self.selectedArea.endingSlot! //UTC
let date = Date().description(with: Locale.current)
let current = date.split(separator: " ")
let currentD:String = String(current[5])
let date1: Date = dateFormatter.date(from: startingSlot)!
let date2: Date = dateFormatter.date(from: endingSlot)!
let currentdate:Date = dateFormatter.date(from: currentD)!
print(date1)
print(date2)
print(current)
if(currentdate >= date1 && currentdate <= date2) {
return true
} else {
return false
}
}
I expect to get true if the current date time lies in between the date1 and date2.
Compare the time by ignoring the date component -
func checkTime() -> Bool {
let dateFormatter: DateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "PKT")
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let startingSlot = "2000-01-01 08:00:00" //UTC
let endingSlot = "2000-01-01 23:00:00" //UTC
let date = Date()
let date1: Date = dateFormatter.date(from: startingSlot)!
let date2: Date = dateFormatter.date(from: endingSlot)!
let currentTime = 60*Calendar.current.component(.hour, from: date) + Calendar.current.component(.minute, from: date) + (Calendar.current.component(.second, from: date)/60) // in minutes
let time1 = 60*Calendar.current.component(.hour, from: date1) + Calendar.current.component(.minute, from: date1) + (Calendar.current.component(.second, from: date1)/60) // in minutes
let time2 = 60*Calendar.current.component(.hour, from: date2) + Calendar.current.component(.minute, from: date2) + (Calendar.current.component(.second, from: date1)/60) // in minutes
print(currentTime)
print(time1)
print(time2)
if(currentTime >= time1 && currentTime <= time2) {
return true
} else {
return false
}
}
Output-
1121
510
1410
true
Related
I have got a date in this format..
2019-12-16 18:30:00 +0000
This is the code I have for that..
var utcTime = "\(dic["dueDate"]!)"
self.dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
self.dateFormatter.locale = Locale(identifier: "en_US")
let date = self.dateFormatter.date(from:utcTime)!
print(date)
I wanted to extract month and date from this string. i.e. from the above date string, I want 'December' & '16' separately.
There are several ways to get the expected result, as an option you can use this code with Calendar:
let utcTime = "2020-01-17T22:01:00"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.locale = Locale(identifier: "en_US")
if let date = dateFormatter.date(from:utcTime) {
let monthInt = Calendar.current.component(.month, from: date)
let dayInt = Calendar.current.component(.day, from: date)
let monthStr = Calendar.current.monthSymbols[monthInt-1]
print(monthStr, dayInt)
}
Welcome to stack overflow.
You can try this :
let calendar = Calendar.current
calendar.component(.year, from: date)
calendar.component(.month, from: date)
calendar.component(.day, from: date)
Hope it helps...
Welcome to stack overflow. Please try this.
func getMonthAndDate(dateString: String) ->(month:String , day:String) {
guard let date = Date.getMonthAndDate(from: dateString, with: "yyyy-MM-dd'T'HH:mm:ss") else {
return ("","")
}
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM"
let month = dateFormatter.string(from: date)
dateFormatter.dateFormat = "dd"
let day = dateFormatter.string(from: date)
return (month,day)
}
extension Date {
static func getMonthAndDate(from str: String, with formatter: String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.current//(abbreviation: "GMT") //Set timezone that you want
dateFormatter.locale = NSLocale.current
dateFormatter.dateFormat = formatter //Specify your format that you want
return dateFormatter.date(from: str)
}
}
Swift 5
Here is the extension you need It returns tuple having Month and date as you wanted to have
extension Date {
func getMonthAndDate() ->(month:String , day:String) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM"
let month = dateFormatter.string(from: self)
dateFormatter.dateFormat = "dd"
let day = dateFormatter.string(from: self)
return (month,day)
}
}
I give you example of month u can get date and month value separately ,
visit link for your format http://userguide.icu-project.org/formatparse/datetime
extension Date {
var month: String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM"
return dateFormatter.string(from: self)
}
}
you can use it in this way:
let date = Date()
let monthString = date.month
try same thing for date, I hope it will work for you... :)
this is an example from your code. I have stored month and day in separate string to show you. You can change according to your requirements.
var utcTime = "2019-12-16 18:30:00 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss z"
dateFormatter.locale = Locale(identifier: "en_US")
let date = dateFormatter.date(from:utcTime)!
print(date) //2019-12-16 18:30:00 +0000
dateFormatter.dateFormat = "MMMM"
let strMonth = dateFormatter.string(from: date)
print(strMonth) //December
dateFormatter.dateFormat = "dd"
let strDay = dateFormatter.string(from: date)
print(strDay) //16
Also you can use Calendar object to get date, month (gives you in digit) and year.
var utcTime = "2019-12-16 18:30:00 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss z"
dateFormatter.locale = Locale(identifier: "en_US")
let date = dateFormatter.date(from:utcTime)!
let calendarDate = Calendar.current.dateComponents([.day, .year, .month], from: date)
let day = calendarDate.day
print(day) //16
let month = calendarDate.month
print(month) //12
let year = calendarDate.year
print(year) //2019
You can get the day, month and year as follows
let yourDate = Calendar.current.dateComponents([.day, .year, .month], from: Date())
if let day = yourDate.day, let month = yourDate.month, let year = yourDate.year {
let monthName = Calendar.current.monthSymbols[month - 1]
// your code here
}
extension String {
func getMonthDay() -> (Int,Int) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ssZ"
let date = dateFormatter.date(from: self) ?? Date()
let calendar = Calendar.current
let month = calendar.component(.month, from: date)
let day = calendar.component(.day, from: date)
return (month, day)
}
}
I am formatting a randomly generated future date but it always returns nil even if the format of dateString is matching and has a value.
But if I try with only "(Date())" instead of newDate, it is successful.
let byDays = Int.random(in: 0...30)
var components = DateComponents()
components.day = byDays
let newDate = String(describing: Calendar.current.date(byAdding: components, to: Date()))
//give the current date output in string
let dateFormatterGet = DateFormatter()
dateFormatterGet.isLenient = true
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
dateFormatterGet.locale = Locale(identifier: "en_US_POSIX")
//describe the new format
guard let date = dateFormatterGet.date(from: newDate) else {
return ""
}
let newDateFormatter = DateFormatter()
newDateFormatter.dateFormat = "MMM dd"
let newStr = newDateFormatter.string(from: date)
print(newStr)
I want the date optional(2019-07-23 17:44:23 +0000) to be printed as Jul 23.
I don't understand the purpose of String(describing: ... You can use the date from the Calendar right away:
func randomFutureDate() -> String? {
let day = Int.random(in: 0...30)
var components = DateComponents()
components.day = day
guard let date = Calendar.current.date(byAdding: components, to: Date()) else {
return nil
}
let newDateFormatter = DateFormatter()
newDateFormatter.dateFormat = "MMM dd"
return newDateFormatter.string(from: date)
}
I have two dates, date1 and date2 and I want days between date1 and date 2
Example:
let date1 = 28-May-2019,
let date2 = 31-May-2019
The expected output
[Tue, Web Thr, Fri]
let date1Str = "28-May-2019"
let date2Str = "31-May-2019"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
dateFormatter.locale = Locale(identifier: "en_US")
var date1 = dateFormatter.date(from:date1Str)!
var date2 = dateFormatter.date(from:date2Str)!
let dayFormatter = DateFormatter()
dayFormatter.dateFormat = "EEE"
while date1 <= date2 {
let dayInWeek = dayFormatter.string(from: date1)
print(dayInWeek)
date1 = Calendar.current.date(byAdding: .day, value: 1, to: date1)!
}
The following code gives you the days between two dates and should account for trickeries with the calendar.
let calendar = Calendar.current
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MMM-yyyy"
let dayFormatter = DateFormatter()
dayFormatter.dateFormat = "EEE"
let dateFrom = dateFormatter.date(from: "28-May-2019")!
let dateTo = dateFormatter.date(from: "31-May-2019")!
var days: [String] = []
var date = dateFrom
while date <= dateTo {
let day = dayFormatter.string(from: date)
days.append(day)
date = calendar.date(byAdding: .day, value: 1, to: date)!
}
print(days)
Try this -
func getWeekdays(dateOne firstDateStr: String, dateTwo secondDateStr: String) -> [String] {
let dateformatter = DateFormatter()
dateformatter.dateFormat = "dd-MMM-yyyy"
guard let firstDate = dateformatter.date(from: firstDateStr),
let secondDate = dateformatter.date(from: secondDateStr) else {
return []
}
let calendar = Calendar.current
let numberOfDays: Int
if firstDate > secondDate {
numberOfDays = (calendar.dateComponents([.day], from: secondDate, to: firstDate).day ?? 0)
} else {
numberOfDays = (calendar.dateComponents([.day], from: firstDate, to: secondDate).day ?? 0)
}
dateformatter.dateFormat = "EEE"
let days = (0...numberOfDays).compactMap { day -> String? in
if let date = calendar.date(byAdding: .day, value: day, to: firstDate) {
return dateformatter.string(from: date)
}
return nil
}
print(days)
return days
}
I'm trying to get the start and end dates of the current month in dd/MM/yyyy format. I tried using extension as answered in this SO Question.But it seems like it's not what I want(the format is different and also it's giving me last month's last date and current month last but one date ). Can some one help me.
Extension Class:
extension Date {
func startOfMonth() -> Date? {
let comp: DateComponents = Calendar.current.dateComponents([.year, .month, .hour], from: Calendar.current.startOfDay(for: self))
return Calendar.current.date(from: comp)!
}
func endOfMonth() -> Date? {
var comp: DateComponents = Calendar.current.dateComponents([.month, .day, .hour], from: Calendar.current.startOfDay(for: self))
comp.month = 1
comp.day = -1
return Calendar.current.date(byAdding: comp, to: self.startOfMonth()!)
}
}
My Struct:
struct Constants{
// keys required for making a Login call (POST Method)
struct LoginKeys {
.....
}
struct RankingKeys {
static let DateFrom = String(describing: Date().startOfMonth()) //giving me 2016-11-30 16:00:00 +0000
static let DateTo = String(describing: Date().endOfMonth())
//2016-12-30 16:00:00 +0000
}
}
Expected Result:
DateFrom = "01/12/2016"
DateTo = "31/12/2016"
You should write this simple code:
let dateFormatter = DateFormatter()
let date = Date()
dateFormatter.dateFormat = "dd-MM-yyyy"
For start Date:
let comp: DateComponents = Calendar.current.dateComponents([.year, .month], from: date)
let startOfMonth = Calendar.current.date(from: comp)!
print(dateFormatter.string(from: startOfMonth))
For end Date:
var comps2 = DateComponents()
comps2.month = 1
comps2.day = -1
let endOfMonth = Calendar.current.date(byAdding: comps2, to: startOfMonth)
print(dateFormatter.string(from: endOfMonth!))
This is what I'm using. Pretty simple but it works.
extension Calendar {
func dayOfWeek(_ date: Date) -> Int {
var dayOfWeek = self.component(.weekday, from: date) + 1 - self.firstWeekday
if dayOfWeek <= 0 {
dayOfWeek += 7
}
return dayOfWeek
}
func startOfWeek(_ date: Date) -> Date {
return self.date(byAdding: DateComponents(day: -self.dayOfWeek(date) + 1), to: date)!
}
func endOfWeek(_ date: Date) -> Date {
return self.date(byAdding: DateComponents(day: 6), to: self.startOfWeek(date))!
}
func startOfMonth(_ date: Date) -> Date {
return self.date(from: self.dateComponents([.year, .month], from: date))!
}
func endOfMonth(_ date: Date) -> Date {
return self.date(byAdding: DateComponents(month: 1, day: -1), to: self.startOfMonth(date))!
}
func startOfQuarter(_ date: Date) -> Date {
let quarter = (self.component(.month, from: date) - 1) / 3 + 1
return self.date(from: DateComponents(year: self.component(.year, from: date), month: (quarter - 1) * 3 + 1))!
}
func endOfQuarter(_ date: Date) -> Date {
return self.date(byAdding: DateComponents(month: 3, day: -1), to: self.startOfQuarter(date))!
}
func startOfYear(_ date: Date) -> Date {
return self.date(from: self.dateComponents([.year], from: date))!
}
func endOfYear(_ date: Date) -> Date {
return self.date(from: DateComponents(year: self.component(.year, from: date), month: 12, day: 31))!
}
}
How to use
let calendar: Calendar = Calendar.current
let startDate = calendar.startOfMonth(Date())
print("startDate :: \(startDate)")
Here is an easy solution in create an extension for Date like following:
extension Date {
func startOfMonth() -> Date {
let interval = Calendar.current.dateInterval(of: .month, for: self)
return (interval?.start.toLocalTime())! // Without toLocalTime it give last months last date
}
func endOfMonth() -> Date {
let interval = Calendar.current.dateInterval(of: .month, for: self)
return interval!.end
}
// Convert UTC (or GMT) to local time
func toLocalTime() -> Date {
let timezone = TimeZone.current
let seconds = TimeInterval(timezone.secondsFromGMT(for: self))
return Date(timeInterval: seconds, since: self)
}}
And then call with your Date instance like that
print(Date().startOfMonth())
print(Date().endOfMonth())
With Swift 3 & iOS 10 the easiest way I found to do this is Calendar's dateInterval(of:for:):
guard let interval = calendar.dateInterval(of: .month, for: Date()) else { return }
Then use a date formatter to print the dates:
let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
let dateText = formatter.string(from: interval.start)
This Extension Gives you expected output as per you want
Here I return date
extension NSDate {
func startOfMonth() -> NSDate? {
guard
let cal: NSCalendar = NSCalendar.currentCalendar(),
let comp: NSDateComponents = cal.components([.Year, .Month], fromDate: self) else { return nil }
comp.to12pm()
let dateformattor = NSDateFormatter()
dateformattor.dateFormat = "yyyy-MM-dd"
dateformattor.timeZone = NSTimeZone.localTimeZone()
let dt2 = dateformattor.stringFromDate(cal.dateFromComponents(comp)!)
print(dt2)
dateformattor.dateFormat = "yyyy-MM-dd"
dateformattor.timeZone = NSTimeZone.init(abbreviation: "UTC")
return dateformattor.dateFromString(dt2)
}
func endOfMonth() -> NSDate? {
guard
let cal: NSCalendar = NSCalendar.currentCalendar(),
let comp: NSDateComponents = NSDateComponents() else { return nil }
comp.month = 1
comp.day = -1
comp.to12pm()
let dateformattor = NSDateFormatter()
dateformattor.dateFormat = "yyyy-MM-dd"
dateformattor.timeZone = NSTimeZone.localTimeZone()
let dt2 = dateformattor.stringFromDate(cal.dateByAddingComponents(comp, toDate: self.startOfMonth()!, options: [])!)
dateformattor.dateFormat = "yyyy-MM-dd"
dateformattor.timeZone = NSTimeZone.init(abbreviation: "UTC")
return dateformattor.dateFromString(dt2)
}
}
internal extension NSDateComponents {
func to12pm() {
self.hour = 12
self.minute = 0
self.second = 0
}
}
**OUTPUT :- **
Start Date of Month :- 2016-12-01 00:00:00 +0000
End Date of Month :- 2016-12-31 00:00:00 +0000
For the sake of completeness, the API dateInterval(of:start:interval:for:) of Calendar assigns the start date and interval (in seconds) of the current month to the inout parameters.
The date formatter considers the current time zone.
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "dd/MM/yyyy"
var startDate = Date()
var interval = TimeInterval()
Calendar.current.dateInterval(of: .month, start: &startDate, interval: &interval, for: Date())
let endDate = Calendar.current.date(byAdding: .second, value: Int(interval) - 1, to: startDate)!
let fromDate = formatter.string(from: startDate)
let toDate = formatter.string(from: endDate)
print(fromDate, toDate)
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