简体   繁体   English

计算两个具有不同语言环境的NSD之间的时差

[英]Calculate time difference between two NSDates with different locales

I have a current NSString in the format of 2010-04-23 00:00:00 and then I'm trying to get the number of days passed from the current day. 我有一个当前的NSString格式为2010-04-23 00:00:00,然后我试图获取从当前日期起经过的天数。 However, I'm not sure how to handle when the user changes their locale to Thailand for example. 但是,例如当用户将语言环境更改为泰国时,我不确定如何处理。

Here is some of the code. 这是一些代码。

NSString *start = @"2010-04-23 00:00:00";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSDate *date = [formatter dateFromString:start];

//Region Format Thailand
NSDate *today = [[NSDate alloc] init];
NSTimeInterval difference =  [today timeIntervalSinceDate:start];
int numberOfDays = difference / 86400;

What would be the correct way to handle this situation so the number of days difference is accurate? 正确处理天数的正确方法是什么?

Dates are complicated. 日期很复杂。

If you want a difference in days, hours, minutes, seconds, that's easy: Convert everything to NSDate, calculate the difference in seconds, convert to days, hours, minutes, seconds. 如果您想要以天,小时,分钟,秒为单位的差异,那很容易:将所有内容转换为NSDate,以秒为单位计算差异,然后转换为天,小时,分钟,秒。

Anything else, you need to first define what results you actually want. 除此以外,您首先需要定义实际想要的结果。 Today at 1am and 11pm is the same day, but today 11pm and tomorrow 1am are different days - even though in the first case the difference is 22 hours, in the second case just two hours. 今天的凌晨1点和11pm是同一天,但是今天的11pm和明天的1am是不同的日子-即使在第一种情况下是22小时,在第二种情况下只有两个小时。 So you have to define what you want. 因此,您必须定义所需的内容。 You have to define for which case you want a result of "0 days" and for which case you want a result of "1 days". 您必须定义在哪种情况下需要“ 0天”的结果,在哪种情况下需要“ 1天”的结果。

And if you change time zones, some dates will move to a different day, some won't. 而且,如果您更改时区,则某些日期将移至另一天,而某些日期则不会。

It's up to you to decide what result you want. 由您决定想要什么结果。 In any case, I'd convert all dates to the relevant time zone, extract the day, and calculate days differences from that. 无论如何,我都会将所有日期转换为相关的时区,提取日期,然后从中计算出天差。

You need to convert the date into epoch time. 您需要将日期转换为纪元时间。
- (NSTimeInterval)timeIntervalSince1970 -(NSTimeInterval)timeIntervalSince1970

After you do that you can use the below code, to find the time difference in seconds and compare them. 完成后,您可以使用下面的代码,找到以秒为单位的时差并进行比较。


NSDate* date1 = [NSDate date]; NSDate * date1 = [NSDate日期];
NSDate* date2 = [NSDate date]; NSDate * date2 = [NSDate日期];
NSTimeInterval secs = [date1 timeIntervalSinceDate:date2]; NSTimeInterval secs = [date1 timeIntervalSinceDate:date2];

if (secs < 0) 如果(秒<0)
{ {
NSLog("less"); NSLog(“ less”);
} }
else if (secs > 0) 否则(秒> 0)
{ {
NSLog("greater"); NSLog(“ greater”);
} }
else 其他
{ {
NSLog(@"same"); NSLog(@“ same”);
return NSOrderedSame; 返回NSOrderedSame;
} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM