Convert String to NSDate in Swift - swift

How to convert this date to NSDate
datestring = /Date(147410000000)/ //String from server response
Expected Output:
12/01/2014
I tried this. But I got nil.
let dateFormatter:NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
let date = dateFormatter.dateFromString(datestring)
return date

"147410000000", i think this the time-interval which you are
getting from server.
In your case,you need to trim the string and convert it From
/Date(147410000000)/ to 147410000000
var string : String = "1408709486" // (Put your string here)
var timeinterval : NSTimeInterval = (string as NSString).doubleValue // convert it in to NSTimeInteral
var dateFromServer = NSDate(timeIntervalSince1970:timeinterval) // you can the Date object from here
println(dateFromServer) // for My Example it will print : 2014-08-22 12:11:26 +0000
// Here i create a simple date formatter and print the string from DATE object. you can do it vise-versa.
var dateFormater : NSDateFormatter = NSDateFormatter()
dateFormater.dateFormat = "yyyy-MM-dd"
println(dateFormater.stringFromDate(dateFromServer)) // And then i can get the string like this : 2014-08-22
Check the comment section. Martin's comment will also help you to resolve your problem.

You just use the wrong function at the last line of your above mentioned code
var dateString = "01-02-2010"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
var dateFromString = dateFormatter.dateFromString(dateString)

Convert Date format in Swift:
let myDate = "2016-09-19 01:25:17"
let dateFormat = NSDateFormatter()
dateFormat.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date = dateFormat.dateFromString(myDate)
dateFormat.dateFormat = "yyyy-MM-dd"
let newDate = dateFormat.stringFromDate(date!)
print(newDate)

Based on Wolverine's code, I've written a function for Swift 3 and iOS10. Feel free to use:
func convertStringTimestampToStringDate(_ dateandTime: String) -> String {
let string : String = dateandTime
let timeinterval : TimeInterval = (string as NSString).doubleValue
let dateFromServer = NSDate(timeIntervalSince1970:timeinterval)
let dateFormater : DateFormatter = DateFormatter()
dateFormater.dateFormat = "MMM dd, yyyy, HH:mm a"
dateFormater.amSymbol = "AM"
dateFormater.pmSymbol = "PM"
let backToString = dateFormater.string(from: dateFromServer as Date)
print(dateFormater.string(from: dateFromServer as Date))
return backToString }
This should bring a solution like e.g.: "Oct 20, 2016, 03:30 AM" from an timestamp as input.

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

Wrong Date coming when i formatting the string to date

When i try format string to date i was given one day but that output showing different date please any one is helping for that.
let my_date = "22-03-1995"
let dateformat = DateFormatter()
dateformat.dateFormat = "DD-MM-yyyy"
let date = dateformat.date(from: my_date)
print(date!)
text_lbl.text = "\(date!)"
My Output is: 1995-01-21 comes like this.
You should use
let my_date = "22-03-1995"
let dateformat = DateFormatter()
dateformat.dateFormat = "dd-MM-yyyy"
let date = dateformat.date(from: my_date)
print(date!)
This will gives you 1995-03-22 00:00:00 +0000 as a result
func changeDateFormatFor(date : String,fromFormat : String = "dd-MM-yyyy", toFormat : String = "yyyy-MM-dd")-> String{
if date == "" {
return ""
}
dateFormatter.dateFormat = fromFormat
let date1 = dateFormatter.date(from: date)
dateFormatter.dateFormat = toFormat
let str = dateFormatter.string(from: date1!)
return str
}

Convert string with timezone to date

I have this type of string and want to convert it to date
"2017-05-27T00:00:00.000+0400"
but none of this formatters convert it to date
"yyyy-MM-dd'T'HH:mm:SSSZ"
"yyyy-MM-dd'T'HH:mm:SSSX"
Your forgot to add ss for seconds so correct formate should be yyyy-MM-dd'T'HH:mm:ss.SSSZ
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = dateFormatter.date(from: "2017-05-27T00:00:00.000+0400")
Your error was that the seconds were missing. So the right format should be: yyyy-MM-dd'T'HH:mm:ss.SSSZ. You can also use an extension for this purpose:
extension String {
var toCustomDate: Date {
return Date.Formatter.customDate.date(from: self)!
}
}
extension Date {
struct Formatter {
static let customDate: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
return formatter
}()
}
var customDate: String {
return Formatter.customDate.string(from: self)
}
}
let str = "2017-05-27T00:00:00.000+0400"
let date = str.toCustomDate
If you have more date formats, then just add them to the extensions.
you can do like this
let dateString = "2017-05-27T00:00:00.000+0400"
let formachanger = DateFormatter()
formachanger .dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
if let dateFromString = formachanger .date(from: dateString) {
formachanger .dateFormat = "yyyy-MM-dd HH:mm"
let stringFromDate = formachanger .string(from: dateFromString)
}
try this function
func getGMTDateFrom(String string : String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy hh:mm:ss zz"
let dateObj = dateFormatter.date(from: string)
return dateObj
}
Change date format according to your need.

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

Convert long month name to int

I understand how to use an NSDateFormatter to convert a month component into a long name string, but how does one convert a month name to an int?
I've been using a switch statement to convert, but I'm thinking there must be a simpler way.
For example, I'd like to convert "May" to 5.
You can use DateFormatter custom format "LLLL" to parse your date string (Month). If you are only parsing dates in english you should set the date formatter locale to "en_US_POSIX":
let df = DateFormatter()
df.locale = Locale(identifier: "en_US_POSIX")
df.dateFormat = "LLLL" // if you need 3 letter month just use "LLL"
if let date = df.date(from: "May") {
let month = Calendar.current.component(.month, from: date)
print(month) // 5
}
Thanks Josh. I've converted the Obj-C code and posted it below for future reference:
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
let components = NSDateComponents()
let formatter = NSDateFormatter()
formatter.dateFormat = "MMMM"
let aDate = formatter.dateFromString("May")
let components1 = calendar!.components(.CalendarUnitMonth , fromDate: aDate!)
let monthInt = components.month
Use MM for the month format. Use stringFromDate to convert your NSDate to a String. Then convert your string to an Int with .toInt()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM"
let monthString = dateFormatter.stringFromDate(NSDate()) // "05"
let monthInt = monthString.toInt() // 5
NSDateFormatter has monthSymbols property. Try:
let formatter = NSDateFormatter()
formatter.calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
let monthString = "September"
let month = find(formatter.monthSymbols as! [String], monthString).map { $0 + 1 }
// -> Optional(9)
let monthString2 = "Foobar"
let month2 = find(formatter.monthSymbols as! [String], monthString2).map { $0 + 1 }
// -> nil