ramya
ramya

Reputation: 451

converting timestamp to nsdate format

I want to convert my timestamp value 1308031456 to NSDate format (which yields the value Tue, 14 Jun 2011 06:04:16 GMT in online web conversion). How would I convert between the two programmatically?

Upvotes: 44

Views: 58938

Answers (5)

incredever
incredever

Reputation: 231

Here is a code piece which lets you convert the unix type timestamp to Formatted Date

NSString * timeStampString =@"1304245000";
NSTimeInterval _interval=[timeStampString doubleValue];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:_interval];
NSDateFormatter *_formatter=[[NSDateFormatter alloc]init];
[_formatter setDateFormat:@"dd.MM.yyyy"];
NSString *_date=[_formatter stringFromDate:date];

This will print _date something like 05.03.2011

Upvotes: 0

vivek
vivek

Reputation: 268

In obj c

double timeStamp = 1513330403393;
NSTimeInterval unixTimeStamp = timeStamp / 1000.0;
NSDate *exactDate = [NSDate dateWithTimeIntervalSince1970:unixTimeStamp];
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"dd/MM/yyy hh:mm a";
NSString  *finalate = [dateFormatter stringFromDate:exactDate];

In Swift

let timeStamp = 1513330403393
let unixTimeStamp: Double = Double(timeStamp) / 1000.0
let exactDate = NSDate.init(timeIntervalSince1970: unixTimeStamp)
let dateFormatt = DateFormatter();
dateFormatt.dateFormat = "dd/MM/yyy hh:mm a"
print(dateFormatt.string(from: exactDate as Date))

Upvotes: 5

KingofBliss
KingofBliss

Reputation: 15115

OBJ - C: Use dateWithTimeIntervalSince1970:,

NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeStamp];

SWIFT: Use init(timeIntervalSince1970:)

let date = NSDate(timeIntervalSince1970:timeStamp)

Upvotes: 147

Jhaliya - Praveen Sharma
Jhaliya - Praveen Sharma

Reputation: 31722

See the various example on date formatting and getting date from timestamp from apple

Use Formatter Styles to Present Dates and Times With the User’s Preferences

Convert TimeStamp to NSDate in Objective-C

Upvotes: 2

Deepak Danduprolu
Deepak Danduprolu

Reputation: 44633

You can use the use the method dateWithTimeIntervalSince1970: to convert the timestamp you've which is the epoch time.

NSDate * myDate = [NSDate dateWithTimeIntervalSince1970:1308031456];

Upvotes: 18

Related Questions