Convert date to timestamp in iOS

5 Solutions Collect From Internet About “Convert date to timestamp in iOS”

Have it a try. “mm” stands for minute while “MM” stands for month.

NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init] ;
[dateFormatter setDateFormat:@"yyyy-MM-dd"] ;
NSDate *date = [dateFormatter dateFromString:@"2014-01-23"] ;
NSLog(@"date=%@",date) ;
NSTimeInterval interval  = [date timeIntervalSince1970] ;
NSLog(@"interval=%f",interval) ;
NSDate *methodStart = [NSDate dateWithTimeIntervalSince1970:interval] ;
[dateFormatter setDateFormat:@"yyyy/MM/dd "] ;
NSLog(@"result: %@", [dateFormatter stringFromDate:methodStart]) ;

Swift

Convert the current date/time to a timestamp:

// current date and time
let someDate = Date()

// time interval since 1970
let myTimeStamp = someDate.timeIntervalSince1970

See also

  • Convert Date to Integer in Swift
  • Creating a Date and Time in Swift
  • How to get the current time as datetime

NSTimeinterval is really a double, being seconds since a particular date (in your case, the start of 1970)

NOTE :- UNIX Timestamp format contains 13 Digits so we need a 1000 multiplication with the result.
And the timestamp must be UTC ZONE not our local Time Zone.

- (void)GetCurrentTimeStamp
    {
        NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
        [objDateformat setDateFormat:@"yyyy-MM-dd"];
        NSString    *strUTCTime = [self GetUTCDateTimeFromLocalTime:@"2014-01-23"];
        NSDate *objUTCDate  = [objDateformat dateFromString:strUTCTime];
        long long milliseconds = (long long)([objUTCDate timeIntervalSince1970] * 1000.0);
        NSLog(@"Local Time = %@---- UTC = %@ ----- TimeSatmp = %ld  ---- TimeStamp = %lld",strTime,strUTCTime,unixTime,milliseconds);
    }

 - (NSString *) GetUTCDateTimeFromLocalTime:(NSString *)IN_strLocalTime
    {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        NSDate  *objDate    = [dateFormatter dateFromString:IN_strLocalTime];
        [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
        NSString *strDateTime   = [dateFormatter stringFromDate:objDate];
        return strDateTime;
    }

[date1 timeIntervalSinceDate:date2] will return seconds from two NSDate objects.

double seconds = [date1 timeIntervalSinceDate:date2];
double milliSecondsPartOfCurrentSecond = seconds - [seconds intValue];

milliSecondsPartOfCurrentSecond