How to convert a parse date object to a string? - ios

beginner alert
I'm trying to query for a date from PFUser and then format it to NSDate so it is more useful. The trouble begins when I try to convert the object to a NSString so I can format it with NSDateFormatter()
var user = PFUser.query()
user.whereKey("username", equalTo: PFUser.currentUser().username)
user.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if error == nil {
for object in objects {
var lastActive = object["lastActive"]
if lastActive != nil {
let newLastActive = lastActive as String //problem starts here!!
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSS'Z'"
let date = dateFormatter.dateFromString(newLastActive)
println("new date \(date)")
}
}
}
}
What is the correct way of doing this? Also, if I don't specify the variable type as AnyObject, it keeps coming out as a optional. How do I get rid of the optional while converting it to String?
edit: the object "lastActive" is a date set by parse cloud, not a string.

If your lastActive cell returns a date you could use:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSS'Z'"
let date = dateFormatter.stringFromDate(lastActive as NSDate)
You dont have to cast your date to string, you will create a date string via the dateformatter.
But if you do so, you could use lastActive as! String insted of lastActive as String
UPDATED
for object in objects {
var lastActive = object["lastActive"]
if lastActive != nil {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSS'Z'"
let date = dateFormatter.stringFromDate(lastActive as NSDate)
println(date)
}
}
I tried with this code above and if you've set your column in parse to date, it should work.

Related

Date formatting in Swift that supports iOS 13+

I bet this is simple. I'm trying in Xcode playgrounds to play with getting a string date
let string = "2022-11-27 00:00:00 +0000"
and converting that into a Date object that's formatted like DD-MM-YYYY
func airdateFormat(_ key: String) -> Date? {
let expectedFormat = Date().formatted(.dateTime.day().month(.wide).year())
let date = try! Date(strategy: expectedFormat)
return date
}
I also tried
func airdateFormat(_ key: String) -> Date? {
guard let dateString = self[key] as? String else { return nil }
let dateFormatted = DateFormatter.dateFormat(fromTemplate: "MM-DD-YYYY", options: Int, locale: Locale?)
return dateFormatted().date(from: dateString)
}
}
I'm parsing this Date string from json hence the guard/else statement
You need to use a format that matches your input to parse the string to a Date
If you want to use the DateFormatter
let string = "2022-11-27 12:34:56 +0000"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
let date = formatter.date(from: string)
and for recent OS versions you use a FormatStyle
let formatStyle = Date.FormatStyle()
.year(.defaultDigits)
.month(.twoDigits)
.day(.twoDigits)
.hour()
.minute()
.second()
.timeZone()
let date = try formatStyle.parse(string)

Save NSDate and Doubles into Entity (CoreData)

I can get it to work fine using just Strings but if I try to use Doubles or NSDates then I get an error:
"Cannot assign value of type "NSDate?" to type "String?"
"Cannot assign value of type "Double?" to type "String?"
#IBAction func save(_ sender: Any) {
if item != nil {
item?.startdate = startDate.text
item?.pickup = pickup.text
item?.miles = miles.text
item?.company = company.text
item?.destination = destination.text
item?.enddate = endDate.text
} else {
let entitydescription = NSEntityDescription.entity(forEntityName: "Entity", in: pc)
let item = Entity(entity: entitydescription!, insertInto: pc)
item.startdate = startDate.text
item.pickup = pickup.text
item.miles = miles.text
item.company = company.text
item.destination = destination.text
item.enddate = endDate.text
}
do {
try pc.save()
} catch {
print(error)
return
}
navigationController!.popViewController(animated: true)
}
Here is what type each field is:
#NSManaged public var startdate: NSDate?
#NSManaged public var pickup: String?
#NSManaged public var miles: Double
#NSManaged public var company: String?
#NSManaged public var destination: String?
#NSManaged public var enddate: NSDate?
You need to convert miles.text, startdate.text and enddate.text to Double, NSDate and NSDate, respectively.
For startdate.text / enddate.text:
I'm not sure how what limit you have set for these values when the item is saved, but you should use a default value just incase the conversion fails. For this example, assume the dates are formatted "5/15/17" which takes the format M/d/y
let defaultDate = NSDate() //current date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "M/d/y"
if let startDateText = startdate.text, let startDate = dateFormatter.string(from: startDateText) as? NSDate {
item?.startdate = startDate
} else {
item?.startdate = defaultDate
}
if let endDateText = startdate.text, let endDate = dateFormatter.string(from: endDateText) as? NSDate {
item?.startdate = endDate
} else {
item?.startdate = defaultDate
}
For miles.text:
Same idea, use a default value incase the conversion failed based on what the text will be for item.miles
if let milesText = miles.text {
item?.miles = Double(miles.text) ?? 0.0 //default is 0.0
} else {
item?.miles = 0.0
}
or an easy one-liner—
item?.miles = Double(miles.text ?? "0.0")
if there's a specific default value you have in mind, just declare it before you assign the item's property,
let defaultMilesStr = "0.432"
item?.miles = Double(miles.text ?? defaultMiles)
Also, just a tip, it's good practice to not leave optionals wrapped when assigning values. So even though there was check to make sure item != nil, it's overall better to safely unwrap item with a "guard" or "if-let". Since you are creating a new item if one doesn't exist, id go with if-let in this case:
if let item = item {
// assign values to item's prop's
// item.startdate = .....
} else if let entityDescription = NSEntityDescription.entity(forEntityName: "Entity", in: pc), let item = Entity(entity: entityDescription, insertInto: pc) {
// assign values to item's prop's
// item.startdate = .....
}
//further execution
Convert your date string to NSdate then you are able to save that
Try this code i have provide my date string you mat change with your format
let dateString = "Thu, 22 Oct 2015 07:45:17 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy hh:mm:ss +zzzz"
dateFormatter.locale = Locale.init(identifier: "en_GB")
let dateObj = dateFormatter.date(from: dateString)
dateFormatter.dateFormat = "MM-dd-yyyy"
Try this :
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = /* date_format_you_want_in_string from
* http://userguide.icu-project.org/formatparse/datetime
*/
let date = dateFormatter.date(from: /* your_date_string */)
and set it as :
item?.date = date
For miles you can use :
if let dMiles = Double(miles.text!) {
item?.miles.text = dMiles
} else {
print("Not a valid Double: \(textField.text!)")
}
Hope it Helps!!

NSDate to display only Date in TableViewCell

I am able to get NSDate to appear as date only and to show it in textfields to add and edit to core data but in the tableviewcell when using the subtitle style it comes out with both the date and time which I don't need thee time.
Any help is appreciated.
the following code is my NSDateFormatter
import Foundation
extension NSDate{
var stringValue: String{
return self.toString()
}
func toString() -> String {
let formatter = NSDateFormatter()
formatter.dateFormat = "dd-MMM-YYYY"
let str = formatter.stringFromDate(self)
return str
}
}
extension String{
var dateValue: NSDate?{
return self.toDate()
}
func toDate() -> NSDate? {
let formatter = NSDateFormatter()
formatter.dateFormat = "dd-MMM-YYYY"
if let date = formatter.dateFromString(self) {
return date
}else{
// if format failed, Put some code here
return nil // an example
}
}
}
the following code is the subtitle style. date is called from cordite
cell.detailTextLabel!.text = "(ddate)"
OK, Found out what I was doing wrong. I added the following line above the cell.detail.textLabel and it works
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMM-dd-yyy"
let dateForText = ddate as? NSDate
cell.detailTextLabel!.text = dateFormatter.stringFromDate(dateForText!)

How do i get a number data and date data from parse and put it to UILabel?

Currently I want to retrieve createdAt and price from parse database and the datatypes for both are Number and NSDate. After I retrieved it I want to pass to UILabel which is date and price respectively. The problem right now is that whenever I tried to run the simulator, both of the UILabel data don't show up while string data type does show up.
My current code
if let createdAt = object?["createdAt"] as? String {
cell.date.text = createdAt
}
if let priceTitle = object?["price"] as? String {
cell.price.text = priceTitle
}
For Date, use NSDateFormatter.stringFromDate method so your code should be:
if let createdAt = object?["createdAt"] as? NSDate {
let dateFormatter = NSDateFormatter()
var theDateFormat = NSDateFormatterStyle.ShortStyle
dateFormatter.dateStyle = theDateFormat
cell.date.text = dateFormatter.stringFromDate(createdAt)
}
createdAt is a special value in Parse. It is PFObject's property and you access it with dot notation. So this is how you should proceed:
if let object = object as? PFObject {
let date = object.createdAt
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH:mm MMMM dd, yyyy"
let dateStr = dateFormatter.stringFromDate(date!)
cell.date.text = dateStr
}

Swift: Cannot convert the expression's type '$T3' to type '$T4'

What I am trying to achieve is convert a birthdate string in this format: 08/15/2014 to an NSDate instance. And then converting the NSDate back to a String but in ISO format.
Why am I receiving this error message?
Cannot convert the expression's type '$T3' to type '$T4'
// birthdateString = 08/15/2014
let birthdateString = KeychainManager.getString(KeychainManager.StaticVars.kFbBirthdate)
let birthdateAsNSDate = Date.parseFacebookBirthdate(birthdateString)
let birthdateAsISOString = Date.getStringFromDate(birthdateAsNSDate)
Date Conversion Class
class Date {
class func parseFacebookBirthdate(birthdateString: String) -> NSDate {
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
return dateFormatter.dateFromString(birthdateString)
}
class func getStringFromDate(date: NSDate) -> String {
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZ"
dateFormatter.timeZone = NSTimeZone.defaultTimeZone()
return dateFormatter.stringFromDate(date)
}
}
I am getting the error on this line:
let birthdateAsNSDate = Date.parseFacebookBirthdate(birthdateString)
I just had to unwrap birthdateString and birthdateAsNSDate when calling my Date functions.
Pretty simple fix =]
let birthdateString = KeychainManager.getString(KeychainManager.StaticVars.kFbBirthdate)
let birthdateAsNSDate = Date.parseFacebookBirthdate(birthdateString!)
let birthdateAsISOString = Date.getStringFromDate(birthdateAsNSDate!)

Resources