Convert date to timestamp in iOS

耗尽温柔 提交于 2019-12-01 09:27:27

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

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

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;
    }
Xeieshan

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

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

milliSecondsPartOfCurrentSecond

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!