I'm trying to convert a string date (2011-06-08T08:05:00.000-08:00) into a NSDate using the following code:
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
//Translate 2011-06-08T08:05:00.000-08:00 into 2011-06-08T08:05:00.000-0800
stringDate = [stringDate stringByReplacingOccurrencesOfString:#":" withString:#"" options:0 range:NSMakeRange([aDate length] - 5, 5)];
[dateFormatter setDateFormat:#"yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSSZZZ"];
NSDate *dateFromString = [dateFormatter dateFromString:stringDate];
At this point, dateFromString is 2011-06-08 16:05:00 +0000. What I actually wanted was for dateFromString to be 2011-06-08 08:05:00 -0800. What am I doing wrong?
Thanks!
So this will not have a direct answer and will assume that your string format will be the same. What we are going to extract the timezone part (last 5 characters) and then calculate how many seconds we are off from GMT. NSTimeZone has a convenience method timeZoneForSecondsFromGMT: that will help us get what we need. This is what you need to add to the code in the question.
NSString * zoneString = [stringDate substringFromIndex:([stringDate length] - 5)];
NSTimeInterval timeInterval = [[zoneString substringToIndex:3] intValue] * 3600;
timeInterval += [[zoneString substringFromIndex:3] intValue] * 60;
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:timeInterval]];
[formatter setDateFormat:#"yyyy'-'MM'-'dd' 'HH':'mm':'ss ZZZ"];
NSLog(#"%#", [formatter stringFromDate:dateFromString]);
Hopefully this helps you. If you've found a better answer already, let us know.
Original Answer
One thing about the NSDate is that the time returned is always in GMT. You can't change that. You will have to use an NSDateFormatter to print it right. Something like this,
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"PST"]];
[formatter setTimeStyle:NSDateFormatterFullStyle];
[formatter setDateStyle:NSDateFormatterFullStyle];
NSLog(#"%#", [formatter stringFromDate:[NSDate date]]);
So setting the timezone for the formatter that does dateForString: won't help. You will need to create a new one when you want them with a different timezone.
Related
I am trying to convert NSDate to UTC Date and this is what I am using..
NSString* dateString= [NSDate utcStringFromDate:[NSDate date] withFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSZ"];
+ (NSString *)utcStringFromDate:(NSDate *)date withFormat:(NSString *)format{
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"]];
[outputFormatter setDateFormat:format];
NSString *timestamp_str = [outputFormatter stringFromDate:date];
[outputFormatter release];
return timestamp_str;
}
This works fine most of the times and gives me a result similar to this.
2013-05-03T05:30:25.18+0000
but at times it gives me a strange value like
2013-04-26T12:03:53 a.m..24+0000
Now I am not sure why it does that..
Thanks for any help.
I need to convert an NSString to an NSDate, but the following code only works as long as the user's device isn't set to 24-Hour time.
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:#"MM/dd/yyyy hh:mm:ss a"];
NSString *aTime = #"2/11/2013 12:00:00 AM";
NSDate *aDate = [formatter dateFromString:aTime];
However, aDate returns null when the device is in 24-Hour time. Any help?
I think you're probably seeing a side effect of the behaviour described by QA1480. Apple has resolved what it presumably thought was developers not obeying locales properly by modifying your prescribed date format unless you explicitly say not to.
You can achieve that by adding:
formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
/* and autorelease if not using ARC */
Which basically says 'the date format I just set is explicitly what I want, please don't modify it in any way'.
I think the following snippet might helps you out.
NSString *dateString = #"09:34 AM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"dd-MM-yyyy";
NSString *stringFromDate = [dateFormatter stringFromDate:[NSDate date]];
dateFormatter.dateFormat = #"dd-MM-yyyy hh:mm a";
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
NSDate *returnDate = [dateFormatter dateFromString:[NSString stringWithFormat:#"%# %#", stringFromDate, dateString]];
try this code
NSString *string = #"2015-11-30 15:00:00";
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"yyyy-MM-dd HH:mm:ss";
[formatter setTimeZone:[NSTimeZone localTimeZone]];
NSDate *date = [formatter dateFromString:string];
date: 2015-11-29 21:30:00 +0000
its in UTC format you can modify this as you need!
Hi Experts of the world,
I ran into a very weird problem:
I am formatting a string representing time from 00-23 (as returned by a Google service) in the following manner:
(passing in a string of lets say 14, should output either 14:00 or 2:00 PM, depends on user local)
+(NSString *) formatTime: (NSString *)timeToBeFormatted {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"HH"];
NSDate *date = [[NSDate alloc] init];
date = [dateFormat dateFromString:timeToBeFormatted];
// Convert date object to desired output format
[dateFormat setTimeStyle:NSDateFormatterShortStyle];
timeToBeFormatted = [dateFormat stringFromDate:date];
return timeToBeFormatted;
}
Everything works fine in all locals worldwide.
However, ONLY if a user has his TIME format set on 12h in a local where the default is 24h the formatter will return NULL ONLY for vales between 12-23.. Pretty weird i would say!
Example:
before formatter 12
after 12:00 AM
before formatter 13
after (null)
Any ideas why this could happen?
Thanks!
Solved! (inspired by the answers above)..
To solve the issue i am creating a specific Locale, then phrasing the stringToDate using this locale. Then i am creating another Locale with the default users preferences and phrasing the dateBackToString using that locale..
+(NSString *) formatTime: (NSString *)timeToBeFormatted
{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
//ADDED//
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
[dateFormat setLocale:enUSPOSIXLocale];
[dateFormat setDateFormat:#"HH"];
NSDate *date = [[NSDate alloc] init];
date = [dateFormat dateFromString:timeToBeFormatted];
//ADDED//
NSLocale *defualtLocale = [[NSLocale alloc] init];
[dateFormat setLocale:defualtLocale];
[dateFormat setTimeStyle:NSDateFormatterShortStyle];
timeToBeFormatted = [dateFormat stringFromDate:date];
return timeToBeFormatted;
}
I guess its quite costly for older devices but in the era of ARC and strong phones it works ;)
NSDateFormatter uses the current locale and time settings for parsing (and outputting) time. If you want to use a specific time format, set the locale for the date formatter yourself.
dateFormat.locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
Also, creating date formatter is expensive, if you call this function often you should cache the date formatter in a static variable.
I was also facing this issue before some time.
Use following code to formate your date as per your need.
+(NSDate *)getGMTDateToView:(NSDate *) availableDate formatter:(NSDateFormatter *)timeFormat {
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
[timeFormat setLocale:enUSPOSIXLocale];
NSTimeInterval timeZoneOffset = [[NSTimeZone defaultTimeZone] secondsFromGMT];
NSTimeInterval gmtTimeInterval = [availableDate timeIntervalSinceReferenceDate] + timeZoneOffset;
[timeFormat setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
[timeFormat setDateStyle:NSDateFormatterShortStyle];
[timeFormat setTimeStyle:NSDateFormatterShortStyle];
enUSPOSIXLocale = nil;
return [NSDate dateWithTimeIntervalSinceReferenceDate:gmtTimeInterval];
}
I found above code from one of apple's document (I have modified(little bit) it as per my need) but unable to find this link right now.
I have the following date: 2011-04-29T14:54:00-04:00
When it runs through the following code to convert it to a date, the date is null for some reason:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate *date = [dateFormatter dateFromString:localDate];
[dateFormatter release];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-mm-dd"];
NSLog(#"%#", [formatter stringFromDate:date]);
Any help would be appreciated
SOLVED:
Ok, I figured it out. For some reason, this method doesn't work.
NSDate *date = [dateFormatter dateFromString:localDate];
This works instead. Hope it helps someone!
NSError *error = nil;
NSDate *date = nil;
[dateFormatter getObjectValue:&date forString:localDate range:nil error:&error];
Ok, I figured it out. For some reason, this method doesn't work.
NSDate *date = [dateFormatter dateFromString:localDate];
This works instead. Hope it helps someone!
NSError *error = nil;
NSDate *date = nil;
[dateFormatter getObjectValue:&date forString:localDate range:nil error:&error];
Try setting the timezone:
dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
and you might need to quote the -'s, :'s, and the Z in your format string (maybe not the -'s and :'s, but I think at least the Z):
[dateFormatter setDateFormat:#"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
Other than those, that is how my date formatter is configured and it works fine.
NSDateFormatter seems to only implement the canonical formats for timezones with 'Z' as described in UTS #35. With no leniency in parsing.
TimeZoneID+/-offset with hours and minutes separated by colon, eg. 2011-04-29T14:54:00GMT-04:00
+/-offset with no separation between hours and minutes, eg. 2011-04-29T14:54:00-0400
Try changing the format of the timezone in your localDate string.
I need to convert a date in this string format:
"2011-01-12T14:17:55.043Z"
to a number like 1294841716 (which is the number of seconds [not milliseconds] since Jan. 1st, 1970). Is there an easy way to do this parsing?
Update: Here is the code I've got so far:
NSString *dateString = #"2011-01-12T14:17:55.043Z";
NSDateFormatter *inFormat = [[NSDateFormatter alloc] init];
[inFormat setDateFormat:#"yyyy-MM-ddTHH:mm:ss.nnnZ"];
NSDate *parsed = [inFormat dateFromString:dateString];
long t = [parsed timeIntervalSinceReferenceDate];
But t comes back as 0 every time.
Use NSDateFormatter to get a NSDate then use - (NSTimeInterval)timeIntervalSince1970 to get the seconds since 1970.
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
[formatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSDate *date = [formatter dateFromString:#"2011-01-12T14:17:55.043Z"];
NSLog(#"Date: %#", date);
NSLog(#"1970: %f", [date timeIntervalSince1970]);
NSLog(#"sDate: %#", [formatter stringFromDate:date]);
[formatter release];