Convert date String to readable date - swift

I get a date from sever like that: "2020-07-20T23:03:11.17926"
I think to make it readable, I have to convert it to timestamp, then convert it to a readable string again.
Here is my code:
func timeStringFromUnixTime(timestamp: String) -> String {
let stringDate = timestamp
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let dateString = dateFormatter.date(from: stringDate)
//get timestamp from Date
if let dateTimeStamp = dateString?.timeIntervalSince1970 {
let date = Date(timeIntervalSince1970: TimeInterval(dateTimeStamp))
dateFormatter.dateFormat = "MMM d, h:mm"
dateFormatter.timeZone = TimeZone(identifier: NSTimeZone.default.identifier)
let localDate = dateFormatter.string(from: date)
return localDate
}
return ""
}
But the problem is, dateString will be equal to nil, so it returns a empty string. Could anyone help me on this?

Replace:
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
with:
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
Z - "RFC 822 GMT format. Can also match a literal Z for Zulu (UTC) time."
SSS - "The milliseconds."
Take a look at NSDateFormatter.com to see more about date formatting.

Related

Creating Date object from timestamp in Swift [duplicate]

I get a crash when running and it points at the dateFormmater.timezone.
The error in the console is:
Could not cast value of type 'Swift.Optional' (0x1192bf4a8) to 'NSTimeZone' (0x1192c0270).
the value of rowEvents.date is "1480134638.0"
Im trying to pull out a Unix timestamp from Firebase saved as a string. Convert it to Date and again save it as a string so I can post it on a cell label.
I got this code from StackOverflow. I plugged in my data and everything is all good until I run it. I guess everything is not all good...
if let lastUpdated : String = rowEvents.date {
let epocTime = TimeInterval(lastUpdated)! / 1000 // convert it from milliseconds dividing it by 1000
let unixTimestamp = NSDate(timeIntervalSince1970: epocTime) //convert unix timestamp to Date
let dateFormatter = DateFormatter()
dateFormatter.timeZone = NSTimeZone() as TimeZone!
dateFormatter.locale = NSLocale.current // NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
dateFormatter.date(from: String(describing: unixTimestamp))
let updatedTimeStamp = unixTimestamp
let cellDate = DateFormatter.localizedString(from: updatedTimeStamp as Date, dateStyle: DateFormatter.Style.full, timeStyle: DateFormatter.Style.medium)
cell.subtitleLabel.text = cellDate
}
The result came from this code here:
let myTimeStamp = self.datePicker?.date.timeIntervalSince1970
let calendarDate = String(describing: myTimeStamp! /** 1000*/)
You can convert unixTimestamp to date using Date(timeIntervalSince1970:).
let unixTimestamp = 1480134638.0
let date = Date(timeIntervalSince1970: unixTimestamp)
If you want to display date in string with specific formate than you can use DateFormatter like this way.
let date = Date(timeIntervalSince1970: unixtimeInterval)
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "GMT") //Set timezone that you want
dateFormatter.locale = NSLocale.current
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm" //Specify your format that you want
let strDate = dateFormatter.string(from: date)
The problem is the line dateFormatter.timeZone = NSTimeZone() as TimeZone!.
Simply use TimeZone instead of NSTimeZone like
dateFormatter.timeZone = TimeZone.current and your code will work.
You might also remove your / 1000 because 1480134638.0 looks more like seconds than milliseconds (since 1970).
Swift 4.1. I created a function. Just pass you timeStamp in function param and function will return data in string data type. You can add more properties to DateFormatter object.
func getDateFromTimeStamp(timeStamp : Double) -> String {
let date = NSDate(timeIntervalSince1970: timeStamp / 1000)
let dayTimePeriodFormatter = DateFormatter()
dayTimePeriodFormatter.dateFormat = "dd MMM YY, hh:mm a"
// UnComment below to get only time
// dayTimePeriodFormatter.dateFormat = "hh:mm a"
let dateString = dayTimePeriodFormatter.string(from: date as Date)
return dateString
}
Using playground all I did was this.
let epochTime = 1547855446
let newTime = Date(timeIntervalSince1970: TimeInterval(epochTime))
print(newTime)
Returns this - 2019-01-18 23:50:46 +0000
extension Double{
func convertDate(formate: String) -> String {
let date = (timeIntervalSince1970: self)
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.current
dateFormatter.locale = NSLocale(localeIdentifier: "(your localization language)" ) as Locale //localization language
dateFormatter.dateFormat = formate //Specify your format that you want let
strDate = dateFormatter.string(from: date)
return strDate
}
}
//usage
let timeStamp:Double = Double(1595407043)
print(timeStamp.convertDate(formate: "EEEE dd/MM/YYY"))
This solution is valid for swift 3 -> 4.2 :
you can add an extension on the Double that returns the date formatted:
extension Double {
// returns the date formatted.
var dateFormatted : String? {
let date = Date(timeIntervalSince1970: self)
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = DateFormatter.Style.none //Set time style
dateFormatter.dateStyle = DateFormatter.Style.short //Set date style
return dateFormatter.string(from: date)
}
// returns the date formatted according to the format string provided.
func dateFormatted(withFormat format : String) -> String{
let date = Date(timeIntervalSince1970: self)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: date)
}
}
example on the above :
let timeStamp = 82749029.0
print(timeStamp. dateFormatted)
//output
//12/11/1994
let timeStamp = 82749029.0
print(timeStamp. dateFormatted(withFormat : "MM-dd-yyyy HH:mm"))
//output
//12-11-1994 13:04

How can I convert date string to time string?

I have a string that looks like this:
"date": "2022-06-30T02:15:00.000+07:00"
And I formatted it to convert to "HH:mm" like this:
func formatTime(string: String) -> String {
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "HH:mm"
let date: Date? = dateFormatterGet.date(from: string)
return dateFormatterPrint.string(from: date ?? Date())
}
The result I want it returns is 09:15, but it returns 02:15.
Can someone tell me where I went wrong? Thank you
"2022-06-30T02:15:00.000+07:00" is the date in the time zone plus 7 hours from the UTC time zone. Than this date in UTC is ā€œ 2022-06-29T19:15:00Zā€
while dateFormatterPrint has a default locale configuration according to the phone settings
You need to set UTC timezone
In this case you might want to convert the DateTime to your local time first:
Convert To LocalTime:
func utcToLocal(dateStr: String) -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
if let date = dateFormatter.date(from: dateStr) {
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "HH:mm"
return dateFormatter.string(from: date)
}
return nil
}
And then:
let utcTime = formatTime(string: "2022-06-30T02:15:00.000+07:00")
let localTime = utcToLocal(dateStr: utcTime)
print(localTime)
The Result:
09:15
I hope this help you solve your problem.

Swift - Facebook Graph API: How to convert date as String to hour:min:sec

I get from Facebook-Graph-API, a date like "2019-05-06T08:39:43+0000" as String.
In swift, how to convert this date to, for example if i live in France (+2), "10:39:43" as String too ?
You set the time zone to +2 hours
let str = "2019-05-06T08:39:43+0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 7200)
if let date = dateFormatter.date(from: str) {
dateFormatter.dateFormat = "HH:mm:ss"
let strPlus2hours = dateFormatter.string(from: date)
print(strPlus2hours)
}

NSDateFormatter dateFromString returns nil for "2015-11-20 13:42:00.000000"

I know there are many similar questions but I can't figure out my problem.
I want to convert a String like "2015-11-20 13:42:00.000000" to NSDate.
My code is like below.
let date:String
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ssZ"
if let value = row["date"]?.asString() {
date = value
let formattedDate = dateFormatter.dateFromString(date) // formattedDate is nil
}
You need to update your dateFormat with following
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSSSS"
As uppercase S represents fraction of second.
More detail about DateTime Format table is available here
Please secure your code by saving ponies !
let date = "2015-11-20 13:42:00.000000"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSSSS"
if let fornmattedDate = dateFormatter.dateFromString(date) as NSDate {
print ("The formated date is \(fornmattedDate)")
} else {
print ("\(date) is not a valid date")
}
Try like this :-
let date = "2015-11-20 13:42:00.000000"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSSSS"
let fornmattedDate = dateFormatter.dateFromString(date) as NSDate!
print ("The formated date is \(fornmattedDate)")
Output:-
The formated date is 2015-11-20 21:42:00 +0000

Change date format in Swift

I have a date format in String value of "2015-08-27" which is "YYYY-MM-DD". I need to convert this to Date format and change the format to "DD-MMM-YYYY". And change it back to String format again to display. So the end result would be "27-AUG-2015".
I have been searching for codes, but couldn't find one.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYY-MM-DD"
let date = dateFormatter.dateFromString("2015-08-27")
dateFormatter.dateFormat = "DD-MMM-YYYY"
let goodDate = dateFormatter.stringFromDate(date!)
Its not tested but I hope it will work.
You can create a class helper like DateHelper and class func:
class func convertDateString(dateString : String!, fromFormat sourceFormat : String!, toFormat desFormat : String!) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = sourceFormat
let date = dateFormatter.date(from: dateString)
dateFormatter.dateFormat = desFormat
return dateFormatter.string(from: date!)
}
And use it:(note format you give on question wrong so it will wrong convert): begin format is YYYY-MM-dd and you want convert to dd-MMM-YYYY)
print(DateHelper.convertDateString("2015-08-27", fromFormat: "YYYY-MM-dd", toFormat: "dd-MMM-YYYY"))
Hope this help.
Just used the function in your code(swift 4.2).
public func convertDateFormatter(date: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"//this your string date format
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
dateFormatter.locale = Locale(identifier: "your_loc_id")
let convertedDate = dateFormatter.date(from: date)
guard dateFormatter.date(from: date) != nil else {
assert(false, "no date from string")
return ""
}
dateFormatter.dateFormat = "HH:mm a"///this is what you want to convert format
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
let timeStamp = dateFormatter.string(from: convertedDate!)
print(timeStamp)
return timeStamp
}
Thanks