There's an exception when I run it.
self.year = value as! NSString
Exception:
Could not cast value of type '__NSDate' (0x1051bd6a0) to 'NSString' (0x10564d8e0).
What am I missing ?
var datePicker = ActionSheetDatePicker(title: "Date:",datePickerMode: UIDatePickerMode.Date, selectedDate: NSDate(),doneBlock: {
picker, value, index in
self.year = value as! NSString
println("year = \(year)")
println("value = \(value)")
return
}, cancelBlock: { ActionStringCancelBlock in return }, origin: sender.superview!.superview)
I think you have to convert date to string via your selected value
let formatter: DateFormatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd-HH-mm-ss"
let dateStr: String = formatter.string(from: value as! Date)
You can use any other format like : "yyyy" or "HH:mm:ss" etc.
and set it to your year variable
self.year = dateStr
Related
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!!
let dateFormater : DateFormatter = DateFormatter()
dateFormater.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormater.date(from: "2016-11-11T11:42:27Z")
print("date is ---->%#",date)
let timestamp = date?.timeIntervalSince1970
print("timestamp is ---->%#",timestamp!)
let str = String(format: "%#",timestamp!)
print("str value is ---->%#",str)
date is -----> 2016-11-11 11:42:27 +000
timestamp is----->1478864547.0
str value is-----> null
Getting date and time stamp value. How to change timestamp value into string. Means 1478864547.0(timestampvalue) to string formate
let str = String(format: "%#",timestamp!) whats wrong this line.
You can simply use let timestampInString = "\(timestamp)".
If it is optional then
if let timestamp = date?.timeIntervalSince1970 {
let timestampInString = "\(timestamp)"
}
The problem is that timestamp is not an object - it's a TimeInterval (which is just a typealias for Double). If you want to use a formatted string, you need to do "%lf".
You are getting null value. timestamp is not a String value so you can no get a String value directly, You have to use Float to String Casting
Do as follow I am sure it will work for you.
let dateFormater : DateFormatter = DateFormatter()
dateFormater.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormater.date(from: "2016-11-11T11:42:27Z")
print("date is ---->%#",date)
let timestamp = date?.timeIntervalSince1970
print("timestamp is ---->%#",timestamp!)
let str = String(format: "%0.0f",timestamp!)
print("str value is ---->%#",str)
TimeInterval is typealias for Double, So use or " 0.0f " " %lf ".
I am try to compare two date-
dateArrayForCompare, is the date which i get from NSDate and, dateArrayServer, is the date which i get from json response.
var dateArrayServer = NSMutableArray()
var dateArrayCalendar = NSMutableArray()
var dateArrayForCompare = NSMutableArray()
let dateHomework:NSArray = allAsign.valueForKey("date") as! NSArray
let homeWork = allAsign.valueForKey("assignmenttype") as! NSArray
for date in dateHomework{
self.dateArrayServer.addObject(date as! String)
}
let sys_date = NSDate()
print("System Date: \(sys_date)")
let df = NSDateFormatter()
df.dateFormat = "dd-MM-yyyy"
let currentDate = df.stringFromDate(sys_date)
print("String Date: \(currentDate)")
for dt in 0...self.dateArrayServer.count-1
{
if(self.dateArrayServer.objectAtIndex(dt) .isEqualToString("\(self.dateArrayForCompare)"))
{
print("Assignment on date: \(self.dateArrayServer.objectAtIndex(dt)) are:\n\(allAsign.objectAtIndex(dt))")
}else
{
print("\(self.dateArrayServer.objectAtIndex(dt)) doesn't match with \(self.dateArrayForCompare) ")
}
}
But get this result-
Something like this (swift 2.2)
for dt in 0 ... dateArrayServer.count-1
{
let date1 = dateArrayServer.objectAtIndex(dt) as! String
for value in dateArrayForCompare.enumerate() {
if date1 == value.element as! String {
print(date1)
}
}
}
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
}
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.