NSDateFormatter not Working for Twitter date

2019-07-25 17:05发布

I am trying to format a date i am getting from twitter using the STTwitter library.

However the code that I've tried so far has not worked.

Code for getting the date from twitter:

NSString *dateString = [status valueForKey:@"created_at"];

This returns the time, date, time zone and year in which the tweet was made which looks messy.

I tried using the following code to convert this and make it neater:

NSDateFormatter *dateFormatter =[[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"MMddHHmm"];

NSDate *dateFromString = [dateFormatter dateFromString:dateString];
NSLog(@"%@", dateFromString);


dateFormatter =[[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"dd MMMM' at 'hhmm a"];
NSString *mydate=[dateFormatter stringFromDate:dateFromString];

And then try to put the result in a text label:

cell.detailTextLabel.text = my date;

Ive tried many different variations of the Date Formatter but none have worked and i have no idea why.

Thanks for your help :)

3条回答
走好不送
2楼-- · 2019-07-25 17:11

I created a gist with Swift implementation of it: https://gist.github.com/appzzman/62339fcd10bbe8fce256 It takes Twitter date and lets you specify the output format of the date.

import UIKit

func parseTwitterDate(twitterDate:String, outputDateFormat:String)->String?{
 let formatter = NSDateFormatter()
 formatter.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"

 var indate = formatter.dateFromString(twitterDate)
 var outputFormatter = NSDateFormatter()
 outputFormatter.dateFormat = "hh:mm a dd:MM:yy"
 var outputDate:String?
    if let d = indate {
    outputDate = outputFormatter.stringFromDate(d)
  }
    return outputDate;
}

var str = "Wed Sep 02 19:38:03 +0000 2009"
var outputDateFormat = "hh:mm a dd:MM:yy"

parseTwitterDate(str, outputDateFormat)
查看更多
The star\"
3楼-- · 2019-07-25 17:14

STTwitter has a category for that:

NSString *s = [tweet valueForKey:@"created_at"];
NSDate *date = [[NSDateFormatter stTwitterDateFormatter] dateFromString:s];
查看更多
太酷不给撩
4楼-- · 2019-07-25 17:30

The date format you are using is not even close the date string used in the result, which is something like Fri Nov 18 20:35:49 +0000 2011.

NSString *dateStr = @"Fri Nov 18 20:35:49 +0000 2011";

NSDateFormatter *dateFormatter= [NSDateFormatter new];
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[dateFormatter setDateFormat:@"EEE MMM dd HH:mm:ss Z yyyy"];

NSDate *date = [dateFormatter dateFromString:dateStr];

The real trick is in the locale used, since the date is localized in english.

查看更多
登录 后发表回答