gpt4 book ai didi

iphone - 使用 timeIntervalSince 1970 的数学题

转载 作者:行者123 更新时间:2023-11-28 18:00:19 24 4
gpt4 key购买 nike

我正在尝试找出我们现在是多少毫秒。我找不到以毫秒为单位返回忽略日期的时间的方法,所以我想我可以根据 timeIntervalSince 1970 方法返回的值来计算它。

我这样做了:

NSLog(@"%f", [[NSDate date] timeIntervalSince1970]);
2013-05-21 16:29:09.453 TestApp[13951:c07] 1369171749.453490

现在我的假设是,因为一天有 86,400 秒,我可以将这个值除以 86400 并得到自 1970 年以来已经过去了多少天。这样做给我 15846.8952483 天。现在,如果我的假设成立,那么今天我是 89.52483%。所以多个 24 小时乘以 86.52659% 会给我 21.4859592 小时 或大约 09:29 PM 的当前时间。正如您从我的 NSLog 中看到的,这与实际时间相差大约 5 小时,但我相信返回的时间间隔是 GMT,因此这比我的时区早 5 小时.

所以我想,好吧,管它呢,我就顺其自然,看看会发生什么。

我通过以下方式切断小数位:

float timeSince1970 = [[NSDate date] timeIntervalSince1970]/86400.0;
timeSince1970 = timeSince1970 - (int)timeSince1970

然后计算今天到目前为止已经发生的毫秒数:

int timeNow = timeSince1970 * 86400000;
NSLog(@"%i", timeNow);
2013-05-21 16:33:37.793 TestApp[14009:c07] 77625000

然后我将毫秒(看起来仍然合适)转换为 NSDate:

NSString *timeString = [NSString stringWithFormat:@"%d", timeNow];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"A"]
NSDate *dateNow = [dateFormatter dateFromString:timeString];
NSLog(@"%@", dateNow);
2013-05-21 16:29:09.455 TestApp[13951:c07] 2000-01-02 03:29:00 +0000

这是我的问题。它不是返回一个附加了一些小时和分钟的 2000-01-01 日期,而是返回一个 2000-01-02 日期。为什么!?

编辑

我通过“删除”我在上面提到的额外 5 小时来让它工作:

int timeNow = (timeSince1970 * 86400000) - (5 * 60 * 60 * 1000);

我不明白为什么这是必要的。如果有人可以解释,我将不胜感激。

编辑 2

也许我应该问一个更基本的问题,关于如何完成我试图完成的任务。我关心时间(例如,下午 4 点很重要,但我不太关心日期)。我一直将这些存储在由以下人员创建的 NSDates 中:

[dateFormatter setDateFormat:@"hh:mm a"];
[dateFormatter dateFromString@"04:00 PM"];

一切似乎都很顺利。现在我想比较当前时间和我保存的时间,看看它是 NSOrderedAscending 还是 NSOrderedDescending 并做出相应的响应。有没有更好的方法来实现这一点?

最佳答案

你需要用NSCalendar根据现在生成NSDateComponents,然后把开始的时分秒都设置为0,这样就可以开始了今天的。然后,您可以使用 NSDate-timeIntervalSinceNow 方法来获取从现在到开始日期之间耗时。

NSCalendar *cal = [NSCalendar currentCalendar];

NSDate *now = [NSDate date];

// BUILD UP NSDate OBJECT FOR THE BEGINNING OF TODAY
NSDateComponents *comps = [cal components: (NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate: now];
comps.hour = 0;
comps.minute = 0;
comps.second = 0;

// USE CALENDAR TO GENERATE NEW DATE FROM COMPONENTS
NSDate *startOfToday = [cal dateFromComponents: comps];

// YOUR ELAPSED TIME
NSLog(@"%f", [startOfToday timeIntervalSinceNow]);

编辑1

如果您只是想比较一些 NSDateObject,您可以查看当时和现在之间的时间间隔是否为负数。如果是,则该日期已过去。

NSDate *saveDate = [modelObject lastSaveDate];
NSTimeInterval difference = [saveDate timeIntervalSinceNow];
BOOL firstDateIsInPast = difference < 0;
if (firstDateIsInPast) {
NSLog(@"Save date is in the past");
}

您也可以使用compare:

NSDate* then = [NSDate distantPast];
NSDate* now = [NSDate date];
[then compare: now]; // NSOrderedAscending

关于iphone - 使用 timeIntervalSince 1970 的数学题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16679887/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com