1

I have a date like :

2014-01-31 17:40:56

How Can I convert it in Timestamp with millisecond?

The result will be 1391170256309 , which is calculated by PHP.

How can I get 2014-01-31 17:40:56 To 1391170256309 in Objective C ?

Pawan Rai
  • 3,434
  • 4
  • 32
  • 42
Myaaoonn
  • 1,001
  • 12
  • 25

3 Answers3

4

Does this work for what you're trying to do?

NSString * dateString = @"2014-01-31 17:40:56";
NSDateFormatter *df=[[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
NSDate *date = [df dateFromString:dateString];

NSTimeInterval since1970 = [date timeIntervalSince1970]; // January 1st 1970

double result = since1970 * 1000;
Logan
  • 52,262
  • 20
  • 99
  • 128
  • Mostly correct. The date formatter locale should be set to en_US_POSIX, and the time interval must be multiplied by 1000 to produce milliseconds. – Hot Licks Mar 08 '14 at 05:12
  • Updated, do you know why it's returning a slightly different value than he specified? – Logan Mar 08 '14 at 05:20
  • It's not clear why the milliseconds value would not always be a multiple of 1000 if the value is derived from the character string and not the other way around. It may be that the OP's numbers came from asking PHP for the date in two forms or from converting numeric to char, vs converting the char form to numeric. – Hot Licks Mar 08 '14 at 13:26
  • If you wanna match a `UNIX_TIMESTAMP()` timestamp format in MySQL (which is only 10 digits), then DON'T multiply by 1000 and use INT: `int result = since1970` – ekashking Jul 16 '20 at 17:44
0

NSDate has a factory method for this specific scenario

- (NSTimeInterval)timeIntervalSince1970

The result that is being calculated in called "epoch time".

Preson
  • 244
  • 2
  • 8
0

Here is sample code I use for NSDate to --> milliseconds :

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

Note : reference date is 1 January 2001, GMT hence multiply it with 1000

Reference - Apple Official Docs

swiftBoy
  • 35,607
  • 26
  • 136
  • 135
  • Generally millisecond time is expressed relative to 1970 -- the UNIX epoch. – Hot Licks Mar 08 '14 at 05:14
  • @HotLicks I was just looking at [Apple docs](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDate/timeIntervalSince1970) , it says same what I have added in answer. Please let me know, Still I will improve my answer. – swiftBoy Mar 08 '14 at 05:23
  • It depends on which reference date you expect. Pretty much all internet timestamps in that form are referenced to 1970, the "UNIX epoch" (which is why the `...since1970` method is provided). Apple references 2001 and some IBM systems reference 2000, but those numbers usually aren't used for internet time. – Hot Licks Mar 08 '14 at 13:33