I am getting start and end dates for my calendar event(while parsing a .ics file) in "20110912T220000" format. How can I convert this to a NSDate to add to add as event(EKEvent)'s startDate property.
If anyone knows please help me soon.
You should use NSDateFormatter for this.
See Data Formatting Guide (the Date & Time Programming Guide may also be interesting)
This is also detailed in this Technical Note in Apple's Q&As. Note that for such situations, you should use the special "en_US_POSIX" locale as explained in this technical note.
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"] autorelease]];
[df setDateFormat:#"yyyyMMdd'T'HHmmss"];
NSDate* parsedDate = [df dateFromString:...];
NSString *dateString = #"20110912T220000";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSLocale *locale = [[[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"] autorelease];
formatter.locale = locale;
formatter.dateFormat = #"yyyyMMdd'T'HHmmss";
NSDate *date = [formatter dateFromString:dateString];
NSLog(#"date: %#", date);
NSLog() output: date: 2011-09-13 02:00:00 +0000
Note, NSLog outputs the data in you local timezone.
Note the single quotes around the 'T' in the date format.
Here is a link to UTS: date/time format characters
Related
I have these following snippet.
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat : #"yyyy/MM/dd"];
NSString *timeStr = #"2015/05/16";
NSDate *timeDate = [formatter dateFromString:timeStr];
But when I print timeDate in console,the output is werid.The year becomes 4003.
4003-05-16 16:00:00 +0000
I test it in iPad 8.3(12F69)(not simulator).System time zone is Beijing.
Any help is appreciated.
The issue is the locale of the formatter. If you want to use gregorian calendar regardless of the device settings, you generally should set locale to en_US_POSIX.
formatter.locale = [NSLocale localeWithLocaleIdentifier:#"en_US_POSIX"];
See Apple Technical Q&A #1480. This is geared towards RFC 3339/ISO 8601 dates, but it really applies anywhere you're trying to use standard calendar for converting date string for internal purposes (i.e. as opposed to those dates that are presented to the end user in the UI, which generally should use the device's locale).
Try this... Just need to add last line while printing output.
NSString *timeStr = #"2015/05/16";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"yyyy-MM-dd";
NSDate *Date = [formatter dateFromString:timeStr];
NSLog(#"Date =%#", [formatter stringFromDate:Date]);
I would like to format a date to display in a uitableview custom cell
The data is passed into the app from a CMS - it is provided as a string in the following format and stored in a date type variable-
2014-04-15 10:10:45 +0000
Our app will initially be UK based - so I need to convert the format into DD/MM/YYYY format.
I tried the following code to parse my date (dateadded which is of type date).
NSDateFormatter *formatter = [NSDateFormatter new];
cellRecP.artDate.text = [formatter stringFromDate:resItem.dateadded];
but this just returns null - i guess the date format provided above is not anything that stringfromdate understands - is there any other way to format date?
Use an 'NSDateFormatter'
NSDateFormatter* newFormatter = [[[NSDateFormatter alloc] init] autorelease];
with this format to parse the string
[newFormatter setDateFormat:#"yyyy-MM-dd hh:mm:ss zzz"];
NSDate* aDate = [newFormatter dateFromString:dateString];
and you should get a valid 'NSDate' object
Try This and also Checkout this All Formate It is really good and helpful.
NSString *yourString = #"2014-04-15 10:10:45 +0000";
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setTimeZone:[NSTimeZone systemTimeZone]];//Set Your Timezone
[df setDateFormat:#"yyyy-MM-dd HH:mm:ss Z"];//You have to set this formate.
NSDate *dd = [df dateFromString:yourString];//This will convert into date;
//Now you can set your formate.
[df setDateFormat:#"dd/MM/yyyy"];
NSString *str = [df stringFromDate:dd];
You need an NSDateFormatter and a proper unicode parse string. NSDateFormatter by default automatically checks the device locale setting the correct output.
This is an example from some code of mine:
NSDateFormatter *dateWriter = [[NSDateFormatter alloc] init];
dateWriter.dateFormat = #"yyyy'-'MM'-'dd' 'HH':'mm':'ss' 'ZZZ";
dateWriter.dateStyle = NSDateFormatterMediumStyle;
dateWriter.timeStyle = NSDateFormatterMediumStyle;
Pay attention that date formatters are pretty expensive to create.
I have a timestamp coming from server that looks like this:
2013-04-18T08:49:58.157+0000
I've tried removing the colons, I've tried all of these:
Converting an ISO 8601 timestamp into an NSDate: How does one deal with the UTC time offset?
Why NSDateFormatter can not parse date from ISO 8601 format
Here is where I am at:
+ (NSDate *)dateUsingStringFromAPI:(NSString *)dateString {
NSDateFormatter *dateFormatter;
dateFormatter = [[NSDateFormatter alloc] init];
//#"yyyy-MM-dd'T'HH:mm:ss'Z'" - doesn't work
//#"yyyy-MM-dd'T'HH:mm:ssZZZ" - doesn't work
//#"yyyy-MM-dd'T'HH:mm:sss" - doesn't work
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"GMT"]];
// NSDateFormatter does not like ISO 8601 so strip the milliseconds and timezone
dateString = [dateString substringWithRange:NSMakeRange(0, [dateString length]-5)];
return [dateFormatter dateFromString:dateString];
}
One of my biggest questions is, is the date format I have above really ISO 8601? All the examples I have seen from people the formats of each are slightly different. Some have ...157-0000, others don't have anything at the end.
This works for me:
NSString *dateString = #"2013-04-18T08:49:58.157+0000";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
// Always use this locale when parsing fixed format date strings
NSLocale *posix = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
[formatter setLocale:posix];
NSDate *date = [formatter dateFromString:dateString];
NSLog(#"date = %#", date);
There is New API from Apple! NSISO8601DateFormatter
NSString *dateSTR = #"2005-06-27T21:00:00Z";
NSISO8601DateFormatter *formatter = [[NSISO8601DateFormatter alloc] init];
NSDate *date = [formatter dateFromString:dateSTR];
NSLog(#"%#", date);
I also have the native API, which is way cleaner... This is the implementation I got in my DateTimeManager class:
+ (NSDate *)getDateFromISO8601:(NSString *)strDate{
NSISO8601DateFormatter *formatter = [[NSISO8601DateFormatter alloc] init];
NSDate *date = [formatter dateFromString: strDate];
return date;
}
Just copy and paste the method, it would do the trick. Enjoy it!
The perfect and best solution that worked for me is:
let isoFormatter = ISO8601DateFormatter();
isoFormatter.formatOptions = [ISO8601DateFormatter.Options.withColonSeparatorInTime,
ISO8601DateFormatter.Options.withFractionalSeconds,
ISO8601DateFormatter.Options.withFullDate,
ISO8601DateFormatter.Options.withFullTime,
ISO8601DateFormatter.Options.withTimeZone]
let date = isoFormatter.date(from: dateStr);
For further more detail, you can refer to apple's official documentation: https://developer.apple.com/documentation/foundation/nsiso8601dateformatter
I have set the locale and timezone but when I format the date, I always get invalid date. The month is always December and year is one less that the specified year. In my case I dont need the day component.
I checked other similar post but it didn't solved the problem.
Any help is appreciated. Thank you.
Here is the code:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.locale = [[[NSLocale alloc] initWithLocaleIdentifier:#"en_US"] autorelease];
dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
[dateFormatter setDateFormat:#"MMM YYYY"];
NSDate *formattedDate = [dateFormatter dateFromString:#"Sep 2013"];
NSLog(#"Date: %#", [dateFormatter stringFromDate:formattedDate]);
[dateFormatter release]; dateFormatter = nil;
OUTPUT: Date: Dec 2012
"YYYY" format is used for "Week of Year" based calendars. Use "yyyy" format specifier instead:
[dateFormatter setDateFormat:#"MMM yyyy"];
I just wanted to add something to the great answer by Vladimir. If you do this before setting your locale, it seems that the date formatting goes crazy. What I had to do was to set the locale before setting the new format, and then use the setDateFormat to change the format based on the locale used.So something like this would do:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setLocale:[NSLocale currentLocale]];//I wanted to set the locale to wherever user is using my app in
[formatter setDateFormat:#"MMM YYYY"];
NSDate *now = [NSDate Date];
NSString *fancyLookingDate = [formatter stringFromDate:now];
NSString *lower = [NSString stringWithFormat:#"%#",[newDates objectAtIndex:0]];
NSString *higher = [NSString stringWithFormat:#"%#",[newDates objectAtIndex:[newDates count]-1]];
NSLog(#"%#",lower);
NSLog(#"%#",higher);
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyy-MM-dd"];
NSDate *dtLower = [df dateFromString:lower];
NSDate *dtHigher = [df dateFromString:higher];
[df release];
NSDateFormatter *df1 = [[NSDateFormatter alloc] init];
[df1 setDateFormat:#"yyyy-MM-dd"];
NSString * lowerDate = [df1 stringFromDate:dtLower];
NSString * higherDate = [df1 stringFromDate:dtHigher];
UILabel *dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 31, self.view.frame.size.width, 30)];
[dateLabel setTextColor:[UIColor grayColor]];
dateLabel.text = [NSString stringWithFormat:#"%# - %#",lowerDate,higherDate];
[self.view addSubview:dateLabel];
Output of lower and higher in Console is:
2011-05-23 14:55:52.767 Vocab[4225:207] 2011-05-23 03:58:22
2011-05-23 14:55:53.781 Vocab[4225:207] 2011-05-23 07:14:56
Here the above code does not work for me. The value for higher and lower are not null but when I try converting it into NSDate using NSDateFormatter then it returns nil.
So dtLower and dtHigher return nil
What could be wrong?
Try setting [df setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
[df setDateFormat:#"yyyy-MM-dd hh:mm:ss"];
Your first date format is wrong.
If you're working with user-visible dates, you should avoid setting a date format string as it's very hard to predict how your format string will be expressed in all possible user configurations. Rather, you should try and limit yourself to setting date and time styles (via -[NSDateFormatter setDateStyle:] and -[NSDateFormatter setTimeStyle:]).
If you're working with fixed-format dates, you should first set the locale of the date formatter to something appropriate for your fixed format. In most cases the best locale to choose is en_US_POSIX, a locale that's specifically designed to yield US English results regardless of both user and system preferences. en_US_POSIX is also invariant in time and between machines (en_US_POSIX works the same on iOS as it does on OSX, and as it it does on other platforms).
Once you've set en_US_POSIX as the locale of the date formatter, you can then set the date format string and the date formatter will behave consistently for all users.
The above info and more can be found in Apple's Technical Q&A QA1480
Here's a snippet of code which implements the recommendation from the above Technical Note:
static NSDateFormatter* dateFormatter = nil;
if (!dateFormatter)
{
dateFormatter = [NSDateFormatter new];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc]
initWithLocaleIdentifier:#"en_US_POSIX"];
[dateFormatter setLocale:enUSPOSIXLocale];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
dateFormatter.dateFormat = #"EEE, dd MMM yyyy HH:mm:ss +0000";
}