Pergunta

I simply have to format the date which comes in this format "2013:07:24 11:05:04" into this format "24-lug-2013", this is the code that i use for do this:

NSDateFormatter *dtF = [[NSDateFormatter alloc] init];
[dtF setDateFormat:@"yyyy:MM:dd hh:mm:ss"];
NSDate *d = [dtF dateFromString:self.creationDate];
NSDateFormatter *dateFormatStr = [[NSDateFormatter alloc] init];
[dateFormatStr setDateFormat:@"d-MMM-yyyy"];
NSString *strDate = [dateFormatStr stringFromDate:d];

NSLog(@"%@",strDate);

This code works right, the problem is that after a few call to this method, sometimes i get a null string, but the format of the input is still the same.

For example with this string as an input "2013:07:24 11:05:04" i get this: 24-lug-2013, which is exactly what i want, but after 7 call in this case, with this input "2013:07:24 13:47:31" i get a null NSDate and consequentially the result string in null.

where is the problem?? Thanks

Foi útil?

Solução 2

i solved by change this line :

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

with this:

[dtF setDateFormat:@"yyyy:MM:dd HH:mm:ss"];

this is because "hh" for hours, meaning values between 1 and 12 -- 14:00:00, eg, will fail. So If you want 24-hour format use "HH"

Outras dicas

Date formatters return nil when the date string that is passed into them does not match the format. The code you've posted uses dateFromString on an input string. If that fails, then your NSDate "d" will be nil, and so the call to stringFromDate will likely also return nil. (Although stringFromDate might also crash if you pass in an NSDate of nil)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top