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);
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With