AppsDev
AppsDev

Reputation: 12499

NSDate format not showing what expected

I have problems printing a date as NSString. I have stored current date and time at certain points of my app lifecycle this way:

NSDate *current = [NSDate date];
long currentTime = [current timeIntervalSince1970];

Now, I need to show those dates in UILabels. I tried this way:

NSDate *date = [NSDate dateWithTimeIntervalSince1970:currentTime];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd/MM/yyyy - HH:mm:ss"];
NSString *stringFromDate = [formatter stringFromDate:date]; 

but I'm not getting the correct date nor the time. What could I be missing?

Thanks!

Upvotes: 1

Views: 129

Answers (2)

gschandler
gschandler

Reputation: 3208

Your currentTime variable is a long, and not an NSTimeInterval (a double). You are losing not only the fractional part (less important), but the upper range of the time interval. Change it to:

NSTimeInterval currentTime = [current timeIntervalSince1970];

Upvotes: 0

Harshal Chaudhari
Harshal Chaudhari

Reputation: 710

Try this,

NSString *stringFromDate=[NSDateFormatter localizedStringFromDate:date dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterMediumStyle];

also you can change the datestyle and timestyle.

Upvotes: 2

Related Questions