Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDateFormatter stringFromDate not returning a string

I'm trying to change a saved date to mountain standard time using NSDateFormatter but it doesn't seem to be working.

it's outputting "currentDate: 2013-02-22 23:20:20 +0000 date With date formatter: other 2000-01-01 07:00:00 +0000" to the console.

It looks like the string isn't being created correctly, but I seem to be calling it in the same way I've seen it called normally.

Suggestions?

    NSTimeZone * mtnTimeZ= [NSTimeZone timeZoneWithAbbreviation:@"MST"];

    NSDate *currentDate = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setTimeZone:mtnTimeZ];

    NSString * timeZ = [dateFormatter stringFromDate:currentDate];

    NSDate * newDate = [dateFormatter dateFromString:timeZ];
    NSLog(@"currentDate: %@ string With dateFormatter: %@ date made from string %@", currentDate, timeZ, newDate);
like image 745
GetSwifty Avatar asked Oct 17 '25 22:10

GetSwifty


2 Answers

You need to set the style for specify date and time formats in order of it to work:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterFullStyle];
[dateFormatter setTimeStyle:NSDateFormatterFullStyle];

[dateFormatter setTimeZone:[NSTimeZone defaultTimeZone]];
NSString * dateCurrentTZ = [dateFormatter stringFromDate:[NSDate date]];

[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"MST"]];
NSString * dateMSTZ = [dateFormatter stringFromDate:[NSDate date]];

NSLog(@"Date In Current Time Zone: %@", dateCurrentTZ);
NSLog(@"Date In MST: %@", dateMSTZ);

In case you want to specify your own format:

NSDateFormatter Documentation

Then look for "Fixed Formats" based on iOS & Mac OSX ver. you are targeting.

like image 83
SAPLogix Avatar answered Oct 21 '25 19:10

SAPLogix


Try putting the following line:

[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];

like this:

NSTimeZone * mtnTimeZ= [NSTimeZone timeZoneWithAbbreviation:@"MST"];

NSDate *currentDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
[dateFormatter setTimeZone:mtnTimeZ];

NSString * timeZ = [dateFormatter stringFromDate:currentDate];

NSDate * newDate = [dateFormatter dateFromString:timeZ];
NSLog(@"currentDate: %@ string With dateFormatter: %@ date made from string %@", currentDate, timeZ, newDate);
like image 23
jdiego Avatar answered Oct 21 '25 20:10

jdiego