Convert date string into proper format

2019-03-07 06:53发布

问题:

I am getting a response from a server and there is a date string I need to convert into a date:

Thu Jun 29 07:15:25 +0000 2017

I am trying to convert the string into a human readable format. Can anyone suggest how to convert this string into date?

回答1:

You need to parse the date string into a Date object using a DateFormatter, then create a string from that Date using another DateFormatter with the output format you want to use.

let created_at = "Thu Jun 29 07:15:25 +0000 2017"
let df = DateFormatter()
df.dateFormat = "E MMM dd HH:mm:ss Z yyyy"
guard let date = df.date(from: created_at) else {return}
let outputFormatter = DateFormatter()
outputFormatter.dateFormat = "EEE, MMM d"
let outputDate = outputFormatter.string(from: date)

If you want to know what date formats look like, use NSDateFormatter.com, which has an interactive interface where you can play around with different date formats and have examples of most common formats as well.



回答2:

This is how you can format it in "Thu Jun 29"

-(NSString *)formatCreatedAt:(NSString *)createdAt
{
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"EEE MMM dd HH:mm:ss Z yyyy"];
    NSDate *date = [dateFormat dateFromString:createdAt];

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"EEE MMM dd"];

    NSString *stringFromDate = [formatter stringFromDate:date];
    return stringFromDate;
}

Pass the value of created_at in this method and the output will be returned in your specified format.