10

For example: assume NSDate tempdate = "05-23-2013". I want this value to be converted into milliseconds.

How can I do this with Objective-C?

Cœur
  • 37,241
  • 25
  • 195
  • 267
himan
  • 449
  • 2
  • 7
  • 20

2 Answers2

29

There is a similar post here and here.

Basically you have get the second form the reference date (1 January 2001, GMT) and multiply it with 1000.

NSTimeInterval seconds = [NSDate timeIntervalSinceReferenceDate];
double milliseconds = seconds*1000;

Cheers!

Community
  • 1
  • 1
alexcristea
  • 2,316
  • 16
  • 18
  • 6
    `timeIntervalSinceReferenceDate` returns a `double`. If you assign that to an integer before multiplying by 1000, then you loose the milliseconds precision! – Martin R Apr 05 '13 at 07:15
  • Yes, sorry my bad. NSTimeInterval is a typedef of double: `typedef double NSTimeInterval;` – alexcristea Apr 05 '13 at 07:19
  • You actually need to use a double to store milliseconds, or you are likely to run into an overflow problem. double milliseconds = seconds*1000; – Michael Feb 04 '14 at 22:38
1

The timeIntervalSince1970 will return seconds from 1970. There are other timeIntervalSince methods if needed.

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDate/timeIntervalSince1970

For reverse conversion, I mean to say from milliseconds to NSDate, refer this stackoverflow article. Convert milliseconds to NSDate

Hope it ll solve your issue.

Community
  • 1
  • 1
AB Bolim
  • 1,997
  • 2
  • 23
  • 47