Date/Time Natural Language Approximation in Swift

Date/Time Natural Language Approximation in Swift

You need two steps. First, convert your date string to an NSDate:

let dateString = "2015-07-14T13:51:05.423Z"

let df = NSDateFormatter()
df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = df.dateFromString(dateString)

(If that's not an exact representation of the strings you get, you'll have to change the date format string to get this to convert).

Next, use NSDateComponentsFormatter to get your desired string:

let formatter = NSDateComponentsFormatter()
formatter.unitsStyle = NSDateComponentsFormatterUnitsStyle.Full
formatter.includesApproximationPhrase = true
formatter.includesTimeRemainingPhrase = false
formatter.allowedUnits = NSCalendarUnit.WeekOfMonthCalendarUnit

if let pastDate = date {
let dateRelativeString = formatter.stringFromDate(pastDate, toDate: NSDate())
}

Today is July 28, so the result for that string is "About 2 weeks". The allowedUnits attribute is a bit field, so you can specify as many unit types as you want to allow.

iPhone: Convert date string to a relative time stamp

-(NSString *)dateDiff:(NSString *)origDate {
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setFormatterBehavior:NSDateFormatterBehavior10_4];
[df setDateFormat:@"EEE, dd MMM yy HH:mm:ss VVVV"];
NSDate *convertedDate = [df dateFromString:origDate];
[df release];
NSDate *todayDate = [NSDate date];
double ti = [convertedDate timeIntervalSinceDate:todayDate];
ti = ti * -1;
if(ti < 1) {
return @"never";
} else if (ti < 60) {
return @"less than a minute ago";
} else if (ti < 3600) {
int diff = round(ti / 60);
return [NSString stringWithFormat:@"%d minutes ago", diff];
} else if (ti < 86400) {
int diff = round(ti / 60 / 60);
return[NSString stringWithFormat:@"%d hours ago", diff];
} else if (ti < 2629743) {
int diff = round(ti / 60 / 60 / 24);
return[NSString stringWithFormat:@"%d days ago", diff];
} else {
return @"never";
}
}

convert string to timestamp and show value to label in swift 2.0

You can use below code.

Swift 2.3

var dateString = (dic2["time"] as! String)
var interval = dateString.doubleValue
var date = NSDate(timeIntervalSince1970: interval)
var format = NSDateFormatter()
format.dateFormat = "dd MMM, YYYY"
var datenewString = format.stringFromDate(date)
cellNotification.lbldatenotificationN.text = "\(datenewString)"

swift 3.1

var dateString: String? = (dic2["time"] as? String)
var interval: TimeInterval? = dateString?.doubleValue
var date = Date(timeIntervalSince1970: interval)
var format = DateFormatter()
format.dateFormat = "dd MMM, YYYY"
var datenewString: String = format.string(from: date)
cellNotification.lbldatenotificationN.text = "\(datenewString)"

Predefined way to convert generic NSStrings to NSDates

You are looking for NSDataDetector and it returns NSTextCheckingResult objects.



Related Topics



Leave a reply



Submit