以毫秒为单位转换日期时间 iOS

Convert DateTime in millisecond iOS

我有日期和时间,我想要的是特定日期和时间的毫秒数

例如:日期是 21-04-2015 日期 (21-04-2015) 的时间是 14:23

那么以毫秒为单位的输出是1429606437692 我想要从 1970 年到今天的毫秒数,最多 14:23 时间 如何在 iOS 中以毫秒为单位获取此日期时间?

请帮助并提前致谢。

以下代码用于将日期和时间转换为毫秒。

NSTimeInterval timeInMiliseconds = [[NSDate date] timeIntervalSince1970];

有关详细信息,请参阅 apple documentation.

----已编辑----

NSString *dateString = @"21-04-2015 14:23";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy HH:mm"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
NSTimeInterval timeInMiliseconds = [dateFromString timeIntervalSince1970]*1000;

为此,您需要将时间间隔乘以 1000,因为时间间隔以秒为单位且为浮点值。所以简单地乘以 1000。为了简单的例子,我添加了选择器

 NSDate *lastOneminute = [NSDate date];
[self performSelector:@selector(timeInterval:) withObject:lastOneminute afterDelay:60.0];

60 秒后选择器调用为:

 - (void)timeInterval:(id)timeGap
{
    NSLog(@"time interval : %@",timeGap);

    NSTimeInterval timeInMiliseconds = [[NSDate date] timeIntervalSinceDate:timeGap] * 1000;
    NSLog(@"milisecond : %f",timeInMiliseconds);
}
double timestamp = [[NSDate date] timeIntervalSince1970];
int64_t timeInMilisInt64 = (int64_t)(timestamp*1000);

#pragma mark - Date


   -(void)DateCalc
    {


        NSDate *today = [NSDate date];
        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@"dd/MM/yyyy"];
        dateString = [dateFormat stringFromDate:today];


        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSDateComponents *comps = [NSDateComponents new];
        comps.day = 7;
        NSDate *sevenDays = [calendar dateByAddingComponents:comps toDate:[NSDate date] options:0];
        [dateFormat setDateFormat:@"dd/MM/yyyy"];
        EndingDate = [dateFormat stringFromDate:sevenDays];


    }

您可以使用下面的代码

    NSString *dateStr = @"21-04-2015 14:23";

    // Convert string to date object
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"dd-MM-YYYY HH:mm"];
    NSDate *date = [dateFormat dateFromString:dateStr];

    ////2014-12-21 08:53:00 +0000 date
    //// 1419151980000 -- milli seconds    
    NSTimeInterval timeInMiliseconds = [date timeIntervalSince1970]*1000;

希望对您有所帮助...!