在NSDate中无法获得当天的开始 [英] Cannot get the beginning of current day in NSDate

查看:52
本文介绍了在NSDate中无法获得当天的开始的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要NSDate格式的当天的开始和结束时间,因为我有一个nspredicate来获取此范围内的数据。所以我写下了一个函数来查找当天的开始,就是这样

I need the beginning and ending of the current day in NSDate format since i have an nspredicate to get the datas between this range. so i wrote down a function to find beginning of current day and this is it

NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:now];
[components setHour:0];
[components setMinute:0];
[components setSecond:0];
NSDate *start = [calendar dateFromComponents:components];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *strFromDate = [formatter stringFromDate:start];

当我尝试nslog strFromDate时,它显示的是当天的确切开始,例如
2013-05-05 00:00:00 +0000
但我需要nsdate格式,因此当我尝试将其转换为nsdate时

when i try to nslog strFromDate it is showing the exact starting of current day like this 2013-05-05 00:00:00 +0000 but i need it in nsdate format so when i try to convert it into the nsdate like this

NSDateFormatter * dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *dateStr = [[NSDate alloc]init];
dateStr = [dateFormat dateFromString:strFromDate];

当我nslog记录时,结果变为2013-05-05 18:30:00 +0000。我已经尝试了很多代码,当我尝试以nsstring格式打印它时,我得到了想要的结果,不知道nsdate出了什么问题。如果有人可以指导我。在此先感谢

and when i nslog it the result becomes 2013-05-05 18:30:00 +0000. i have tried a lot of codes and when i tried to print it in nsstring format i got the desired result do not know what goes wrong with nsdate. If anyone could guide me. Thanks in advance

推荐答案


,当我nslog记录时,结果变为 2013 -05-05 18:30:00 +0000

请仔细阅读该结果。最后的 +0000 是有意义的。这表示格林尼治标准时间(伦敦时间)。这就是说伦敦的时间是 18:30:00 。但是,假设您在印度。就是在午夜之后的 5:30 。而这正是您想要的。

Read that result carefully. The +0000 at the end is meaningful. It means GMT (the time in London). So this is saying that the time is 18:30:00 in London. But let's say you are in India. That is 5:30 later, which is midnight. And that is exactly what you wanted.

这篇关于在NSDate中无法获得当天的开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆