How to handle different date time formats using NSDateFormatter - iphone

I have a String with a datetime format: "YYYY-MM-DD HH:MM:SS".
I use this in my source code:
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"%e. %B %Y"];
NSString *test = [formatter stringFromDate:#"2010-01-10 13:55:15"];
I want to convert from "2010-01-10 13:55:15" to "10. January 2010".
But my implementation does not work.
What's wrong here?
Thanks a lot in advance & Best Regards.
Updated source code:
[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4];
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"%Y-%m-%d %H:%M:%S"];
NSString *test1 = [formatter stringFromDate:#"2010-01-10 13:55:15"];
NSDateFormatter *formatter1 = [[[NSDateFormatter alloc] init] autorelease];
[formatter1 setDateFormat:#"%d. %M4 %Y"];
NSString *test2 = [formatter1 stringFromDate:test1];

A date formatter can only handle one format at a time. You need to take this approach:
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [f dateFromString:#"2010-01-10 13:55:15"];
NSDateFormatter *f2 = [[NSDateFormatter alloc] init];
[f2 setDateFormat:#"d. MMMM YYYY"];
NSString *s = [f2 stringFromDate:date];
s will now be "10. January 2010"

Here are a few examples of working with data formatters from my code. You should be able to take any one of these functions and tweak it for your format.
USAGE
NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [Constants getTitleDateFormatter];
NSString *dateString = [dateFormatter stringFromDate:today];
[dateFormatter release];
FUNCTIONS
+ (NSDateFormatter *) getDateFormatterWithTimeZone {
//Returns the following information in the format of the locale:
//YYYY-MM-dd HH:mm:ss z (Z is time zone)
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[NSLocale currentLocale]];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
[dateFormatter setTimeStyle:NSDateFormatterLongStyle];
return dateFormatter;
}
+ (NSDateFormatter *)dateFormatterWithoutYear {
NSDateFormatter *dateFormatter = [Constants getDateFormatterWithTimeZone];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSString *format = [dateFormatter dateFormat];
format = [format stringByReplacingOccurrencesOfString:#"/yy" withString:#""];
NSRange secondSpace;
secondSpace.location = format.length-2;
secondSpace.length = 1;
format = [format stringByReplacingCharactersInRange:secondSpace withString:#""];
[dateFormatter setDateFormat:format];
return dateFormatter;
}
+ (NSDateFormatter *) dateFormatterMonthDayOnly {
NSDateFormatter *dateFormatter = [Constants getDateFormatterWithTimeZone];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSString *format = [dateFormatter dateFormat];
format = [format stringByReplacingOccurrencesOfString:#"/yy" withString:#""];
NSRange range;
range.location = 0;
range.length = 3;
format = [format substringWithRange:range];
[dateFormatter setDateFormat:format];
return dateFormatter;
}
+ (NSDateFormatter *) getTitleDateFormatter {
//Returns the following information in the format of the locale:
//MM-dd-yyyy hh:mm:ssa
NSDateFormatter *dateFormatter = [Constants getDateFormatterWithTimeZone];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
NSString *format = [dateFormatter dateFormat];
NSRange secondSpace;
secondSpace.location = format.length-2;
secondSpace.length = 1;
format = [format stringByReplacingOccurrencesOfString:#"/" withString:#"-"];
format = [format stringByReplacingCharactersInRange:secondSpace withString:#""];
[dateFormatter setDateFormat:format];
return dateFormatter;
}

First off, make sure you set the behavior to 10.4 - more modern, works better in my experience.
[dateTimeFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
Next, you can't use the same format to parse and format if they have 2 different string representations, so use 2 formatters, or change the string format between parsing and then formatting.
Also make sure you consider the formatting options:
http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW1
lowercase is e is the day of week, lowercase d is the day of the month.
For month, use MMMM, not B.

You want to use [NSFormatter dateFromString:] to convert your string-based date to an NSDate instance. From there you want to use stringFromDate with the NSDate, not the string as you have written above. I'm not sure about using the same NSDateFormatter for both parsing and formatting - you may need two separate instances to handle the different format styles.

Related

NSDateFormatter returns nil in iphone 5 ios 6.1

Can someone tells me whats wrong with my time formatter? when i used ipod 6.0 the time formatter works. but when i used iphone 5 6.1 the time formatter returns nil.
Here are my codes regarding to the timeFormatter.
NSDateFormatter *tempFormatter = [[[NSDateFormatter alloc]init] autorelease];
[tempFormatter setDateFormat:#"yyyy-MM-dd hh:mm"];
NSString *dateandtime = #"2013-05-27 19:00";
//set end date and time
NSDateFormatter *tempFormatterTo = [[[NSDateFormatter alloc]init] autorelease];
[tempFormatterTo setDateFormat:#"yyyy-MM-dd hh:mm"];
NSString *dateandtimeTo = #"2013-05-27 20:00";
NSDate *startDate = [tempFormatter dateFromString:dateandtime];
NSDate *endDate = [tempFormatterTo dateFromString:dateandtimeTo];
Thanks in advance. please help me.
Try to use this format. HH used for 24 hour format.
[tempFormatter setDateFormat:#"yyyy-MM-dd HH:mm"];
Try This
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd hh:mm"];
NSDate* d = [df dateFromString:#"2013-05-27 19:00"];
NSLog(#"%#", d);
here problem in your Format change it to yyyy-MM-dd HH:mm also use my bellow method when you want to convert any NSString date to NSDate .. This is my custom method just paste this method in your .m class..
-(NSDate *)convertStringToDate:(NSString *) date dateFormat:(NSString*)dateFormat{
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
NSDate *nowDate = [[[NSDate alloc] init] autorelease];
[formatter setDateFormat:dateFormat];// set format here which format in string date
date = [date stringByReplacingOccurrencesOfString:#"+0000" withString:#""];
nowDate = [formatter dateFromString:date];
// NSLog(#"date============================>>>>>>>>>>>>>>> : %#", nowDate);
return nowDate;
}
and use above method like bellow...
NSDate *startDate = [self convertStringToDate:#"2013-05-27 19:00" dateFormate:#"yyyy-MM-dd HH:mm"];
NSDate *endDate = [self convertStringToDate:#"2013-05-27 20:00" dateFormate:#"yyyy-MM-dd HH:mm"];

How to format data from string variable

I have a NSString that keeps date:
1900-01-01T11:00:00
I need to format it, so I have a formatter:
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"dd/MM/yyyy hh:mm:ss a"];
How to format this string now?
NSString* formatedDateString = [df ???];
Create a date formatter, that returns a date object for for the given string, create a second date formatter, that returns a string in the desired format from that date.
NSDateformatter *inputFormatter = [[NSDateformatter alloc] init];
[inputFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss"];
[inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"]];
NSDate *date = [inputFormatter dateFromString:dateString];
NSDateformatter *outputFormatter = [[NSDateformatter alloc] init];
[outputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"]];
[outputFormatter setDateFormat:#"dd/MM/yyyy hh:mm:ss a"];
NSString *outputString = [outputFormatter stringFromDate:date];
But you could also let the output date formatter decide the style in respect to the locale:
NSDateformatter *outputFormatter = [[NSDateformatter alloc] init];
[outputFormatter setDateStyle:NSDateFormatterShortStyle];
[outputFormatter setTimeStyle:NSDateFormatterShortStyle];
NSString *outputString = [outputFormatter stringFromDate:date];
for a american locale, you should now cat the desired format.
if you want to enforce format "dd/MM/yyyy hh:mm:ss a" for the user, you should also set the locale of the output date formatter.
a complete command line example.
int main(int argc, const char * argv[])
{
#autoreleasepool {
NSString *dateString1 = #"2012-12-31T11:00:00";
NSString *dateString2 = #"2012-12-31T14:00:00";
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"]];
[inputFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss"];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"]];
[outputFormatter setDateFormat:#"dd/MM/yyyy hh:mm:ss a"];
NSDate *date1 = [inputFormatter dateFromString:dateString1];
NSDate *date2 = [inputFormatter dateFromString:dateString2];
NSString *outputString1 = [outputFormatter stringFromDate:date1];
NSString *outputString2 = [outputFormatter stringFromDate:date2];
NSLog(#"%#", outputString1);
NSLog(#"%#", outputString2);
}
return 0;
}
If you dont set the locale like [outputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"]]; it will lead do a ugly mix of formats with user's sefault locale, if it not happend to be 'en_US'
ie in German: 31/12/2012 02:00:00 nachm. This is a format not used in german.
To support user's language and locale you should instead use the different styles.
The q&a rmaddy provided indicates, that there are rare cases, where the parse format gets rewritten. To avoid this, set the input formatted's format to a certain locale, like [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"]];
You need to create two date formatter, one for parsing, one for formatting; Your parsing format is "yyyy-MM-ddThh:mm:ss" and your output format is "dd/MM/yyyy hh:mm:ss a". So, something like this :
NSString * targetString = #"1900-01-01'T'11:00:00";
NSDateFormatter *parseFormat = [[NSDateFormatter alloc] init];
[parseFormat setDateFormat:#"yyyy-MM-ddThh:mm:ss"];
NSDate * date = [parseFormat dateFromString:targetString];
NSDateFormatter * outputFormat = [[NSDateFormatter alloc] init];
[outputFormat setDateFormat:#"dd/MM/yyyy hh:mm:ss a";
NSString * outputString = [parseFormat stringFromDate:date];
example for getting current date :
-(void) getDate
{
NSString *theDate;
NSString *theTime;
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd"];
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:#"HH:mm:ss"];
NSDate *now = [[NSDate alloc] init];
theDate = [dateFormat stringFromDate:now];
theTime = [timeFormat stringFromDate:now];
//2012-09-21 02:00:00
self.deviceCurrentTime=[NSString stringWithFormat:#"%# %#",theDate,theTime];
}

ios: String to Date conversion

I am trying to convert my date from NSString to NSDate using following code
NSDateFormatter *dateformatter = [[NSDateFormatter alloc]init];
[dateformatter setDateStyle:NSDateFormatterShortStyle];
[dateformatter setTimeStyle:NSDateFormatterNoStyle];
[dateformatter setDateFormat:#"dd/MM/yyyy"];
NSDate *myDate = [[NSDate alloc] init];
currMonth = 3;
currYear = 2012;
NSString *str = [NSString stringWithFormat:#"01/%2d/%d", currMonth, currYear];
str = [str stringByReplacingOccurrencesOfString:#" " withString:#"0"];
myDate = [dateformatter dateFromString:str];
NSLog(#"myStr: %#",str);
NSLog(#"myMonth: %2d",currMonth);
NSLog(#"myYear: %d",currYear);
NSLog(#"myDate: %#",myDate);
Above code is giving me wrong date. Can anyone please help?
What is your output? Keep in mind, that NSDate is in UTC.
2012-03-01 00:00:00 (GMT+1) is 2012-02-39 23:00:00 (UTC)
Another tip:
%02 formats your integers with leading zeros.
Try this:
-(NSDate *)dateFromString:(NSString *)string
{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
[dateFormat setLocale:locale];
[dateFormat setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSTimeInterval interval = 5 * 60 * 60;
NSDate *date1 = [dateFormat dateFromString:string];
date1 = [date1 dateByAddingTimeInterval:interval];
if(!date1) date1= [NSDate date];
[dateFormat release];
[locale release];
return date1;
}
Tell me if it helps u :]
try
NSDateFormatter *dateformatter = [[NSDateFormatter alloc]init];
[dateformatter setDateStyle:NSDateFormatterShortStyle];
[dateformatter setTimeStyle:NSDateFormatterNoStyle];
[dateformatter setDateFormat:#"dd/MM/yyyy"];
NSDate *myDate = [[NSDate alloc] init];
int currMonth = 3;
int currYear = 2012;
NSString *str = [NSString stringWithFormat:#"01/%2d/%d", currMonth, currYear];
str = [str stringByReplacingOccurrencesOfString:#" " withString:#"0"];
//SET YOUT TIMEZONE HERE
dateformatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:#"PDT"];
myDate = [dateformatter dateFromString:str];
NSLog(#"myStr: %#",str);
NSLog(#"myMonth: %2d",currMonth);
NSLog(#"myYear: %d",currYear);
NSLog(#"myDate: %#",myDate);

Need help for specific date format

I have next date string,
2011-08-30T11:44:54.345-04:00
Help me to compose right format to parse it with dateFromString:
You need to eliminate the last colon (timezone, "-04:00" -> "-0400"), as Z will take something like "-0800", then you can give this a try:
NSString *dateString = #"2011-08-30T11:44:54.345-04:00";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-ddEHH:mm:ss.SSSZ"];
NSDate *date = [dateFormat dateFromString:dateString];
[dateFormat release];
For more information on date formatting, refer to this page.
This is following the tilo's answer but with few things added.
NSString *dateString = #"2011-08-30T11:44:54.345-04:00";
NSRange range = [dateString rangeOfString:#":" options:NSBackwardsSearch];
dateString = [dateString stringByReplacingOccurrencesOfString:#":" withString:#"" options:0 range:range];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-ddEHH:mm:ss.SSSZ"];
NSDate *date = [dateFormat dateFromString:dateString];
[dateFormat release];
You would get the required format.

iphone: NSDateFormatter how to show time in 24 hours format?

NSDateFormatter *formatter1=[[NSDateFormatter alloc]init];
[formatter1 setDateFormat:#"HHmmss MMddyyyy"];
NSDate *finalDate =[formatter1 dateFromString:testTime];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[lblpickUpTime setText:[formatter stringFromDate:finalDate]];
[formatter release];
[formatter1 release];
where testTime = #"201518 07122011"; and I want the result in 24 hours time
e.g. 20.15 rather than 8:15 PM
and is there any better way to do this?
Try by setting
[formatter setDateFormat:#"HH:mm"]; // replacement for [formatter setTimeStyle:NSDateFormatterShortStyle];
Alternate method (without using any formatters):
NSRange range;
range.location = 2;
range.length = 2;
NSString *dateString = [NSString stringWithFormat:#"%#:%#",[myString substringToIndex:2],[myString substringWithRange:range]];
If you specify a format instead of using NSDateFormatterShortStyle, you can have the output in any format you want. For example:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd 'at' HH:mm"];
[lblpickUpTime setText:[formatter stringFromDate:finalDate]];
[formatter release];