How to extract the date from Swift String as NSDate? - ios

My date is "2017-05-04 13:46:36.0". How can I filter only the date from this?
I have used this function:
func toDate(dateString : String, dateFormat : String = "yyyy-MM-dd'T'HH:mm:ssX")-> NSDate!{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = dateFormat
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let convertedDate = dateFormatter.dateFromString(dateString)
return convertedDate
}
let date = "2017-05-04 13:46:36.0"
now I have tried tried to set:
lbl.text = String.toDate(dateString: date, dateFormat: "yyyy-MM-dd")
But it always returns nil and crashes the app? Why is this happening?

You have wrong Parameter passed
var dateString: String = "2017-05-04 13:46:36.0"
var dateFormatter1 = DateFormatter()
dateFormatter1.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
var yourDate: Date? = dateFormatter1.date(from: dateString)
dateFormatter1.dateFormat = "yyyy-MM-dd"
Rule of Date formatter is you must set date format same like your string while you are getting date from string , if mismatch then you will get null
Swift 2
var dateString: String = "2017-05-04 13:46:36.0"
var dateFormatter1: NSDateFormatter = NSDateFormatter()
dateFormatter1.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
var yourDate: NSDate = dateFormatter1.dateFromString(dateString)
dateFormatter1.dateFormat = "yyyy-MM-dd"
print("\(dateFormatter1.stringFromDate(yourDate))")

let dateString = "2017-05-04 13:46:36.0"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.0"
let date = dateFormatter.date(from: dateString)!
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.string(from: date)

Related

Date format in Swift ios

how i can implement this date format 1st July,2021 17:00.My current code is
func changeFormat(_ toFormat: String,_ dateStr: Date?) -> String{
let date = dateStr ?? Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = toFormat
return dateFormatter.string(from: date)
}
func covertStringToDate(_ date: String) -> Date {
let isoDate = date
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter.date(from:isoDate)!
}
If u want to convert any Date object to this format do this.
let date = Date()
//create the date format without the day
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "MMMM,yyyy HH:mm"
let dateWithoutDay = dateFormatter.string(from: date)
//get the day from the date
let dayFormatter = DateFormatter()
dayFormatter.locale = Locale(identifier: "en_US_POSIX")
dayFormatter.dateFormat = "d"
let day = dayFormatter.string(from: date)
//create a number formatter to get st/nd/rd/th suffix
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .ordinal
let dayWithSuffix = numberFormatter.string(from: NSNumber(value:Int(day)!))
print("\(dayWithSuffix!) \(dateWithoutDay)") // --> 3rd September,2022 22:52
If u want to convert this type of date (1st July,2021 17:00 ) to a Date object do this.
let dateString = "1st July,2021 17:00"
let dateSuffix = dateString.components(separatedBy: CharacterSet.decimalDigits).joined().prefix(2)
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "dd'\(dateSuffix)' MMMM,yyyy HH:mm"
let date = dateFormatter.date(from: "1st July,2021 17:00")
print(date!) // ->> 2021-07-01 11:30:00 +0000

How to convert string to NSDate in Swift?

How can I convert a string like 05/18/2017 this to NSDate?
I am trying to convert this string to NSDate so that I can extract the day as 18 and month as 05 and year as 2017. How can I convert this or can extract those values from strings.
func toDate(dateString : String, dateFormat : String = "yyyy-MM-dd'T'HH:mm:ssX")-> NSDate!{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = dateFormat
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let convertedDate = dateFormatter.dateFromString(dateString)
return convertedDate
}
Now in code below selectedValue is 05/18/2017 but NSDateFromString always shows nil value:
let nsdateFromString = String.toDate(selectedValue)
What can I do in this case?
The default dateFormat value of your function toDate not matching the selectedValue's date format, so you need to pass dateFormat argument also with your method call with value MM/dd/yyyy.
let nsdateFromString = String.toDate(dateString: selectedValue, dateFormat: "MM/dd/yyyy")
**in SWIFT 3.0,**
let strDate = "12/21/2017"
let datefrmter = DateFormatter()
datefrmter.dateFormat = "mm/dd/yyyy"
let date = datefrmter.date(from: strDate)
print(date)
func convertSToD(date : String)-> Date?{
if date != "NA"{
let interval = Double(date)
let dateFormat = Date(timeIntervalSince1970: interval!)
return dateFormat
}
return nil
}
Try this :-
func toDate(dateString : String, dateFormat : String = "MM/dd/yyyy")-> NSDate!{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = dateFormat
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let convertedDate = dateFormatter.dateFromString(dateString)
return convertedDate
}
Convert Current date and time
let formatter1 = DateFormatter()
let date1 = Date.init()
formatter1.dateFormat = "dd-MMM-yyyy hh:mm a"
let days = formatter1.string(from: date1 as Date)
print(days)
//in Swift 3.0 converting string to NSDate with its format
let dateString = self.scoring_date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z"
dateFormatter.locale = Locale.init(identifier: "en_GB")
self.dateObj = dateFormatter.date(from: dateString! as String )!
dateFormatter.dateFormat = "MM-dd-yyyy"
print("Dateobj: \(dateFormatter.string(from: self.dateObj))")
//converting NSDate to String
let today = Date()
today.toString(dateFormat: "dd-MM")

Converting String to Date using dd-MM-yyyy get nil in Xcode 8 in Swift 3.0

if I choose date like let dateString = "2014-01-12", How would I convert string to
dateFormatter.dateFormat = "yyyy-MM-dd"
and then in below format
dateFormatter.dateFormat = "dd-MM-yyyy"
I get nil values in Xcode 8 in Swift 3.0
{
let dateString = "2014-01-12"
dateFormatter.locale = Locale(identifier:"ja_JP")
dateFormatter.dateFormat = "dd-MM-yyyy"
print(dateFormatter.date(from:dateString))
}
or
let dateString = "2014-01-12"
dateFormatter.dateFormat = "yyyy-MM-dd"
var s = dateFormatter.date(from: dateString)! as Date
dateFormatter.dateFormat = "dd-MM-yyyy"
s = dateFormatter.date(from: dateString)! as Date
print("SecondDate\(s)")
In Xcode 7 it works fine.
If you want to convert to date formate yyyy-MM-dd to dd-MM-yyyy then your last line should be.
let dateString = "2014-01-12"
dateFormatter.dateFormat = "yyyy-MM-dd"
var s = dateFormatter.date(from: dateString)
dateFormatter.dateFormat = "dd-MM-yyyy"
Get formatted date like this
let dateStr = dateFormatter.string(from: s)
Instead of
s = dateFormatter.date(from: dateString)! as Date
You need to just change format of DateFormatter and get it as the String.
Need to change date string into "date string" as Date then you can change into your particular format. For every format you need to do this first.
You can use the code below.
Swift 3
extension String {
func changeDate(_ mydate:String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = DateFormatter.Style.long
dateFormatter.dateFormat = "yyyy-MM-dd"
let convertedDate = dateFormatter.date(from: mydate)
dateFormatter.dateFormat = "dd-MM-yyyy"
let date = dateFormatter.string(from: convertedDate!)
return date
}
}
You can use this
let dateString = "2014-01-12"
let dateFormatterNew = DateFormatter()
dateFormatterNew.dateFormat = "yyyy-MM-dd"
let date = dateFormatterNew.date(from: dateString)! as Date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
let dateNew = dateFormatter.string(from: date )
print(dateNew)
do it like this
let datestring = "2014-01-12"
let dateF = NSDateFormatter()
dateF.dateFormat = "yyyy-MM-dd"
let firstDate = dateF.dateFromString(datestring)
dateF.dateFormat = "dd-MM-yyyy"
let newDateString = dateF.stringFromDate(firstDate!)
print("NEW DATE FORMAT IS : \(newDateString)")

Convert date string swift

I have a date string in this format:
2016-06-20T13:01:46.457+02:00
and I need to change it to something like this:
20/06/2016
Previously I have always used this library -> SwiftDate to manipulate the dates, but it doesn't work now.
I tried also something like:
let myDate = self.dateNoteDict[indexPath.row]!
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss.SSSSxxx"
let date = dateFormatter.dateFromString(myDate)
print("date -> \(date)")
but it doesn't work. How can I do?
Thanks in advance.
The standard ISO8601 date format with fractional seconds and time zone is
yyyy-MM-dd'T'HH:mm:ss.SSSZ
let myDate = "2016-06-20T13:01:46.457+02:00"
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") // edited
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = dateFormatter.dateFromString(myDate)!
dateFormatter.dateFormat = "dd/MM/yyyy"
let dateString = dateFormatter.stringFromDate(date)
Swift 3:
let myDate = "2016-06-20T13:01:46.457+02:00"
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // edited
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = dateFormatter.date(from:myDate)!
dateFormatter.dateFormat = "dd/MM/yyyy"
let dateString = dateFormatter.string(from:date)
In macOS 10.13+, iOS 11+ ISO8601DateFormatter is an alternative as input formatter
let myDate = "2016-06-20T13:01:46.457+02:00"
let inputFormatter = ISO8601DateFormatter()
inputFormatter.formatOptions = [.withFullDate, .withFullTime, .withFractionalSeconds]
let date = dateFormatter.date(from:myDate)!
let outputFormatter = DateFormatter()
outputFormatter.locale = Locale(identifier: "en_US_POSIX")
outputFormatter.dateFormat = "dd/MM/yyyy"
let dateString = dateFormatter.string(from:date)
I always use this code while converting String to Date .
(Swift 3)
extension String
{
func toDate( dateFormat format : String) -> Date
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
if let date = dateFormatter.date(from: self)
{
return date
}
print("Invalid arguments ! Returning Current Date . ")
return Date()
}
}
and just call like . .
print ( "2016-06-20T13:01:46.457+02:00".toDate(dateFormat: "yyyy-MM-dd'T'HH:mm:ss.SSSZ") )
//Capital HH for 24-Hour Time
I always use this code while converting String to Date. (Swift 4.2)
let myDate = datePicker.date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = myDate
dateFormatter.dateFormat = "dd/MM/yyyy"
let dateString = dateFormatter.string(from:date)
print(dateString)
You can try manually also:
let myDate = "2019-02-22T08:21:11+0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = myDate
dateFormatter.dateFormat = "dd/MM/yyyy"
let dateString = dateFormatter.string(from:date)
print(dateString)

Convert String to NSDate with Swift 2

I'm trying to convert a string to NSDate here is my code
let strDate = "2015-11-01T00:00:00Z" // "2015-10-06T15:42:34Z"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-ddTHH:mm:ssZ"
print ( dateFormatter.dateFromString( strDate ) )
I keep getting nil as a result
The "T" in the format string needs to be single quoted so it will not be consider a symbol:
Swift 3.0
let strDate = "2015-11-01T00:00:00Z"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from:strDate)
print("date: \(date!)")
Output:
date: 2015-11-01 00:00:00 +0000
Swift 2.x
let strDate = "2015-11-01T00:00:00Z"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.dateFromString(strDate)
print("date: \(date!)")
Output:
date: 2015-11-01 00:00:00 +0000
See: Date Field SymbolTable.
This includes the need to enclose ASCII letters in single quotes if they are intended to represent literal text.
For swift 4 and swift 3.2 updated answer.
here all Date related function mentioned.
hop these function useful for you.
1=> Timestamp to Date
func timeStampToDate(_timestamp : String, _dateFormat : String) -> String{
var LOCAL_TIME_ZONE: Int { return TimeZone.current.secondsFromGMT() }
var date = Date(timeIntervalSince1970: TimeInterval(_timestamp)!)
date += TimeInterval(LOCAL_TIME_ZONE as NSNumber)
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "GMT") //Set timezone that you want
dateFormatter.locale = NSLocale.current
dateFormatter.dateFormat = _dateFormat //Specify your format that you want
let strDate = dateFormatter.string(from: date)
return strDate
}
2=> Date to String
func DateToString(date : Date, dateFormatte : String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormatte
print("Dateobj: (dateFormatter.string(from: dateObj!))")
return (dateFormatter.string(from: date as Date))
}
3=> String to date
func StringDateToDate(dateString : String, dateFormatte : String) -> Date {
//let dateString = "Thu, 22 Oct 2015 07:45:17 +0000"
//let dateFormatte = "EEE, dd MMM yyyy hh:mm:ss +zzzz"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormatte
let dateObj = dateFormatter.date(from: dateString)
if dateObj == nil {
return Date()
}
return dateObj!
}

Resources