get time and date by NSDate

NSDate *localDate = [NSDate date]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; dateFormatter.dateFormat = @”MM/dd/yy”; NSString *dateString = [dateFormatter stringFromDate: localDate]; NSDateFormatter *timeFormatter = [[NSDateFormatter alloc]init]; timeFormatter.dateFormat = @”HH:mm:ss”; NSString *dateString = [timeFormatter stringFromDate: localDate]; There are many many different ways to represent the date and time so check NSDateFormatter for more info.

Fuzzy date algorithm

There is a property in NSDateFormatter – “doesRelativeDateFormatting”. It appears only in 10.6/iOS4.0 and later but it will format a date into a relative date in the correct locale. From Apple’s Documentation: If a date formatter uses relative date formatting, where possible it replaces the date component of its output with a phrase—such as “today” … Read more

Convert ISO 8601 to NSDate

This works for me: NSString *dateString = @”2013-04-18T08:49:58.157+0000″; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@”yyyy-MM-dd’T’HH:mm:ss.SSSZ”]; // Always use this locale when parsing fixed format date strings NSLocale *posix = [[NSLocale alloc] initWithLocaleIdentifier:@”en_US_POSIX”]; [formatter setLocale:posix]; NSDate *date = [formatter dateFromString:dateString]; NSLog(@”date = %@”, date);

Truncate NSDate (Zero-out time)

unsigned int flags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay; NSCalendar* calendar = [NSCalendar currentCalendar]; NSDateComponents* components = [calendar components:flags fromDate:date]; NSDate* dateOnly = [calendar dateFromComponents:components]; date is the date you want to remove the time from. This separates the date and time and creates a new date with the default time (00:00:00). EDIT To take … Read more

Swift convert time to time ago

I’ll just update the Truongky’s answer for Swif 3: extension Date { func getElapsedInterval() -> String { let interval = Calendar.current.dateComponents([.year, .month, .day], from: self, to: Date()) if let year = interval.year, year > 0 { return year == 1 ? “\(year)” + ” ” + “year ago” : “\(year)” + ” ” + “years … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)