将String转换为Date并获取差异 [英] Convert String to Date and fetch the difference
问题描述
我有2个字符串格式的日期
hi i have 2 dates in string format
base_date_string = 10-12-01 12:00:00current_date_string = 10-12-23 10:18:00以上两个值都在字符串中
base_date_string = 10-12-01 12:00:00 current_date_string = 10-12-23 10:18:00 both the above values are in string
我想获取这两个日期之间经过的天数
i want to get the number of days elapsed between these 2 dates
我尝试使用NSDateFormatters将它们转换为NSDate,然后得到区别.我意识到字符串无法正确转换为NSDate
I tried to convert them to NSDate using NSDateFormatters and then getting the difference. I realised that string does not properly converts to NSDate
当我转换为nsdate时,我得到了base_date ::: 2010-12-01 06:30:00 +0000current_date ::::: 2010-12-23 04:48:19 +0000(时间部分不完美)
when i convert to nsdate i got base_date:::2010-12-01 06:30:00 +0000 current_date::::2010-12-23 04:48:19 +0000 (the time portion is not perfect)
Formatter类是:
Formatter class that i used is:
NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
[formatter1 setDateFormat:@"yy-MM-dd HH:mm:ss"];
NSDate *base_date = [formatter1 dateFromString:@"10-12-01 12:00:00"];
[formatter1 release];
NSDateFormatter *formatter2 = [[NSDateFormatter alloc] init];
[formatter2 setDateFormat:@"yy-MM-dd HH:mm:ss"];
NSDate *current_date = [formatter2 dateFromString:current_date_string];
[formatter2 release];
//从当前日期开始对基准日期进行计数,以获取经过的天数
//subrtrcation of basedate from current date to get elapsed number of days
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *diff = [calendar components:(NSDayCalendarUnit)
fromDate:base_date toDate:current_date options:0];
int date_value = [diff day];
请提供任何帮助
推荐答案
30秒:
So using the dates in your question...
NSTimeInterval difference = [current_date timeIntervalSinceDate:base_date];
difference = fabs(difference);
NSLog(@"there are %f seconds between %@ and %@", difference, current_date, base_date);
修改
好,所以问题不在于日期差异.您会发现您输入的字符串比您返回的日期早5和1/2小时.
ok, so the problem is not date differencing. You're observing that the string you're inputting is 5 and 1/2 hours ahead of the date you're getting back.
好吧,让我们来看一下.返回的日期为格林尼治标准时间(以 +0000
表示).在此之前的5和1/2小时是印度使用的时区.所以.你在印度吗如果您愿意,那么只需在 NSDateFormatter
上的 -setTimezone:
.
Well, let's look at this. The date returned is in GMT time (as denoted by the +0000
). 5 and 1/2 hours ahead of that is the timezone used in India. So. Are you in India? If you are, then this is just a matter of needing to -setTimezone:
on your NSDateFormatter
.
这篇关于将String转换为Date并获取差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!