简体   繁体   中英

iOS NSDateFormatter returns wrong date

dbVoiceDate is wrong why?

I tried a lot!

NSDateFormatter *formatterVoice = [[NSDateFormatter alloc] init];
formatterVoice.dateFormat = @"dd-MMM-yyyy hh:mm:ss";
dbVoiceDate = [formatterVoice dateFromString:dbDateStr];

Getting response:

Printing description of dbDateStr:

03-Oct-2016 10:43:59

Printing description of self->dbVoiceDate :

2016-10-03 05:02:16 +0000

thanks in advance.

format it like this

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MMM-yyyy hh:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];

//then do your coding.

Try this:-

NSString *dateString = @"Thu Oct 3 10:34:58 +0000 2016";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEE MMM dd hh:mm:ss Z yyyy"];
NSDate *date = [dateFormatter dateFromString:dateString];
NSLog(@"%@", date);
[dateFormatter setDateFormat:@"dd-MM-yyyy hh:mm:ss"];
NSString *finalDateStr = [dateFormatter stringFromDate:date];
NSLog(@"%@", finalDateStr);

Try this following code:

+(NSString*)getDateWithMonthSpelling:(NSString*)dateStr
{
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"dd/MM/yyyy";
    NSDate *yourDate = [dateFormatter dateFromString:dateStr];
    dateFormatter.dateFormat = @"dd MMM yyyy";
    NSString*myDate = [dateFormatter stringFromDate:yourDate];
    return myDate;
}

You need to check the timezone. If it is in GMT set timezone to GMT, like this:

[youDateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];

Else you can use your local timezone like this:

[youDateFormat setTimeZone:[NSTimeZone systemTimeZone]];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM