Convert date to timestamp in iOS

27,975

Solution 1

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]) ;

Solution 2

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

Share:
27,975
user2799156
Author by

user2799156

Updated on July 09, 2022

Comments

  • user2799156
    user2799156 almost 2 years

    How do you convert any given date to milliseconds? For example, 2014-01-23 to timestamp conversion.

    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]);
    

    Output result: 1970/30/01

  • user2799156
    user2799156 over 10 years
    result should be 2014-01-23,why 1970/30/01
  • Alex Brown
    Alex Brown over 10 years
    I assume your initial dateFormatter is incorrectly configured.
  • tryKuldeepTanwar
    tryKuldeepTanwar almost 7 years
    hey i'm struggling with the time like i have a particular date and a time for example 1-january-2018 9:00 am how to get the timestamp of the particular date with particular time...