I am a bit new to swift and IOS coding. I have a NSdate array which is retrieved from parse "CreatedAt" column. I need to convert that array to a string array so I can use it as an input for a text label in tableview cells.
//I try the below, I defined resultsDateArrayString as string array variable, and resultsDateArray as NSdate array variable.
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "hh:mm"
resultsDateArrayString = dateFormatter.stringFromDate(self.resultsDateArray)
cell.postDateTxt.text = self.resultsDateArrayString[indexPath.row]
This is a highly inefficient way of formatting the dates into a String since it instantiates a new NSDateFormatter each time. Consider creating a constant NSDateFormatter for the class as an optimisation.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell
let formatter = NSDateFormatter()
formatter.timeZone = NSTimeZone.systemTimeZone()
formatter.dateStyle = .ShortStyle
formatter.timeStyle = .ShortStyle
cell.textLabel!.text = formatter.stringFromDate(resultsDateArray[indexPath.row])
return cell
}
UPDATE 1
To get that hh:mm format that you've mentioned in your updated question, then simply delete the line formatter.dateStyle = .ShortStyle
I'd use a map function with NSDateFormatter wrapped around each date with the output format you want.
var dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = ...
var strings = dates.map{dateFormatter.stringFromDate($0)}
Related
Hello i get my date from Datepicker that gets saved to a string then uploaded to Firebase. The string is then recieved to the phone. The problem is that i want to convert this string to NSDate when i retrieve it.
This is how i get a string from datepicker
func datePickerChanged(datePicker:UIDatePicker){
var dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
var strDateFrom = dateFormatter.stringFromDate(datePicker.date)
fromDate = strDateFrom
print(fromDate)}
When i retrieve the date i get it as a string this is the print
print(self.membershipActiveTo)
And this is the print log
5/11/16, 2:35 PM
And below is the line of code i have tried to convert to string but it only returns nil
let strDate = self.membershipActiveTo // "2015-10-06T15:42:34Z"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm"
print ( dateFormatter.dateFromString( strDate ) )
There are things to consider when working with dates and one of them is how to store the date in a consistent format that can be easily worked with for different uses. In your case, you may want to sort by date and if the data is stored like this
5/11/16, 2:35 PM
It's not going to be sortable. So, a different format is needed and here's one possible example
20160511143500
Here's some code to manipulate dates:
Write a nicely formatted date to Firebase
let d = NSDate()
//create a custom date string & save in firebase
let dateFormatterCustom = NSDateFormatter()
dateFormatterCustom.dateFormat = "yyyyMMddhhmmss"
let customDateString = dateFormatterCustom.stringFromDate(d)
print(customDateString) //prints "20160511023500" just for testing
let timesRef = self.myRootRef.childByAppendingPath("time_test")
let thisTimeRef = timesRef.childByAutoId()
let timeChildRef = thisTimeRef.childByAppendingPath("timestamp")
timeChildRef.setValue(customDateString)
Firebase now has this
time_test
-KFerAcANQv4pN1Pp4yW
timestamp: "20160418033309"
Then to read in from Firebase:
let timesRef = self.myRootRef.childByAppendingPath("time_test")
timesRef.observeEventType(.ChildAdded, withBlock: { snapshot in
let timeStamp = snapshot.value.objectForKey("timestamp") as! String
print(timeStamp) //still looks like 20160418033309
let shortDateString = self.timeStampToDateString(timeStamp)
print(shortDateString) //prints 4/18/16, 3:33 AM
})
and the function that converts the timestamp style string to a human readable one
func timeStampToDateString(stamp: String) -> String {
//create a custom date string & create a date object from it
let dateFormatterCustom = NSDateFormatter()
dateFormatterCustom.locale = NSLocale(localeIdentifier: "US_en")
dateFormatterCustom.dateFormat = "yyyyMMddhhmmss"
let d = dateFormatterCustom.dateFromString(stamp)!
//create a short date style string and format the string
let dateFormatterShortStyle = NSDateFormatter()
dateFormatterShortStyle.dateStyle = NSDateFormatterStyle.ShortStyle
dateFormatterShortStyle.timeStyle = NSDateFormatterStyle.ShortStyle
let dateString = dateFormatterShortStyle.stringFromDate(d)
return dateString
}
There's a lot of extra code in this example so it could be shortened considerably but I wanted to leave in all of the steps.
I have two strings stored with CoreData and I would like to display them both in a tableview cell.
I tried:
cell.textLabel.text = data.valueForKey("firstName, lastName") as? String
with "firstName" being one key and "lastName" being the other, but this won't compile. When I enter multiples like this:
cell.textLabel.text = data.valueForKey("firstName") as? String
cell.textLabel.text = data.valueForKey("lastName") as? String
it only displays the last value (in this case "lastName") in the tableview cell.
Can anyone tell me how to display both the "firstName" and "lastName" on a tableview cell simultaneously?
cell.textLabel.text = data.valueForKey("firstName") as? String
cell.textLabel.text = data.valueForKey("lastName") as? String
Your second assignment is overwriting the first. You need to concatenate the strings together, presumably with a space or a comma between them.
let firstname = data.valueForKey("firstName") as? String
let lastname = data.valueForKey("lastName") as? String
let separator = ", "
let label = lastname + separator + firstname
cell.textLabel.text = label
I have a label I want to update daily and automatically? in some specific time. How could the code be.. I have searched every where about how to updating the label daily.
the NSdate and NStimer label working . And also datepicker if the user want to look at forward events.
I think it is something with, 'if' the date is.. }else{... and something like that
Thanks
edit:
If I already have these codes in my app then there will be something wrong
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
NSDate *nowDate = [NSDate date];
self.currentDateLabel.text = [dateFormatter stringFromDate:nowDate];
Try this code for any comparison between dates... You should not compare date in the form of string. Compare the dates before conversion to string. Convert the self.serverDate into date format using dateFromString function of the formatter by specifying the exact date format as that of the dateString. Then compare the dates using following function.
-(void) callAfterSixtySecond:(NSTimer*) t
{
NSDate *today = [NSDate date]; // current date
NSDate *newDate = self.serverDate; // other date
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:#"HH:mm"];
NSDate *todayTime = [formatter dateFromString:[formatter stringFromDate:today]];
NSDate *requiredTime = [formatter dateFromString:[formatter stringFromDate:newDate]];
NSComparisonResult result;
result = [todayTime compare:requiredTime ]; // comparing two dates
if(result == NSOrderedAscending)
NSLog(#"today is less");
else if(result == NSOrderedDescending)
NSLog(#"newDate is less");
else if(result == NSOrderedSame)
NSLog(#"Both dates are same"); // time has reached. Update Label using setText method of label
else
NSLog(#"Date cannot be compared");
}
You will need to run this method every minute using an NSTimer...
NSTimer* myTimer = [NSTimer scheduledTimerWithTimeInterval: 60.0 target: self
selector: #selector(callAfterSixtySecond:) userInfo: nil repeats: YES];
I have a JSON feed coming into my app, one of the fields is a combined date & time string which I need to split into discrete date and time strings for display in a table cell. An example of input from the JSON is:
2012-01-18 14:18:00.
I'm getting a bit confused with the date formatter, and clearly I'm not doing it right - I've tried a number of tutorials but most just seem to show how to format a date.
I've tried something a little like this to get just the time:
NSDictionary *rowData = [self.raceData objectAtIndex:[indexPath row]];
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
[dateFormat setDateFormat:#"h:mma"];
NSDate *raceDate = [dateFormat dateFromString:[rowData valueForKey:#"race_time"]];
NSString *raceTime = [dateFormat stringFromDate:raceDate];
but on output raceTime is just null.
Any help appreciated.
maybe the format should be more like
[dateFormatter setDateFormat:#"yyyy-MM-dd 'at' HH:mm"];
have a look at http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html
might clear things up abit
Right, I have this working - it's probably a bit messy but here's what I did:
NSDictionary *rowData = [self.raceData objectAtIndex:[indexPath row]];
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
[dateFormat setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate* raceDate = nil;
NSError* dateError = nil;
NSRange dateRange = NSMakeRange(0, [[rowData valueForKey:#"race_time"] length]);
[dateFormat getObjectValue:&raceDate forString:[rowData valueForKey:#"race_time"] range:&dateRange error:&dateError];
[dateFormat setDateFormat:#"HH.mm"];
NSString *raceTime = [dateFormat stringFromDate:raceDate];
I can now output raceTime as a standalone time. I had to use getObjectValue:forString:range:error: to parse the original string to a date before changing the formatting and parsing it again.
As I'm using this in a table I suspect I'll need to use a static formatter so it doesn't slow everything down - if anyone can give a best practice on doing that I'd appreciate it.
If you are sure that the input string format wouldn't change – you might use something similar to:
NSString *date = nil;
NSString *time = nil;
NSDictionary *rowData = [self.raceData objectAtIndex:[indexPath row]];
NSString *raceTime = [rowData valueForKey:#"race_time"];
NSArray *dateParts = [raceTime componentsSeparatedByString:#" "];
if ([dateParts count] == 2) {
date = [dateParts objectAtIndex:0];
time = [dateParts objectAtIndex:1];
}
I'm having trouble converting an ISO 8601 timestamp into an NSDate. I tried to use NSDateFormatter, but I can't get it to work with the UTC time offset that appears on the end of the timestamps. To explain, I would like to convert a timestamp such as the following into an NSDate: 2011-03-03T06:00:00-06:00. My question is: How do I deal with the "-06:00" part? I tried using yyyy-MM-dd'T'HH:mm:ssZ as my date format string but it doesn't work. Any suggestions?
No need to remove the :'s. To handle the "00:00" style timezone, you just need "ZZZZ":
Swift
let dateString = "2014-07-06T07:59:00Z"
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZ"
dateFormatter.dateFromString(dateString)
Objective-C
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
dateFormat.locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
NSString *input = #"2013-05-08T19:03:53+00:00";
[dateFormat setDateFormat:#"yyyy-MM-dd'T'HH:mm:ssZZZZ"]; //iso 8601 format
NSDate *output = [dateFormat dateFromString:input];
NSLog(#"Date output: %#", output);
In my case I received something like that:
"2015-05-07T16:16:47.054403Z"
And I had to use:
"yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSSZ"
The problem is the : character inside the timezone offset. You could explicitly remove just that colon, or remove all of the colons, and then proceed. For example:
NSString *s = #"2011-03-03T06:00:00-06:00";
s = [s stringByReplacingOccurrencesOfString:#":" withString:#""];
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:#"yyyy-MM-dd'T'HHmmssZZ"];
NSDate *d = [f dateFromString:s];
NSLog(#"%#", d);
This logs:
EmptyFoundation[5088:707] 2011-03-03 12:00:00 +0000
Here is the method that I use:
-(NSDate *)dateFromISO8601String:(NSString *)dateString{
if (!dateString) return nil;
if ([dateString hasSuffix:#"Z"]) {
dateString = [[dateString substringToIndex:(dateString.length-1)] stringByAppendingString:#"-0000"];
}
dateString = [dateString stringByReplacingOccurrencesOfString:#":" withString:#""];
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateFormat = #"yyyy-MM-dd'T'HHmmssZ";
return [dateFormatter dateFromString:dateString];
}
Converting ISO 8601 timestamp into NSDate In Swift:
let dateFormatter = NSDateFormatter()
let inputDate = "2015-06-18T19:00:53-07:00"
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZ" //iso 8601
let outputDate = dateFormatter.dateFromString(inputDate)
println(outputDate!) //optional implicitly
Or optional explicitly:
if let outputDate = dateFormatter.dateFromString(inputDate) {
println(outputDate) //no need !
}
Apple supports a separate format for ISO 8601 format
Objective C
NSISO8601DateFormatter *formater = [[NSISO8601DateFormatter alloc]init];
NSString *string = [formater stringFromDate:[NSDate date]];