我在服务器上有一些日期字符串,我想在我的应用程序中解析它,获取日期并将其显示在我的应用程序有的日历上,而不是设备日历上。
为了做到这一点,我就是这样做的
_dateFromatter = [[NSDateFormatter alloc] init];
[_dateFromatter setDateFormat:@"dd-MMM-yyyy"];
[_dateFromatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
[_dateFromatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
_gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[_gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
NSDate *historyDate = [_dateFromatter dateFromString:[data objectForKey:@"dateStringFromServer"]];
if(historyDate != nil)
{
NSDateComponents *weekdayComponents = [_gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit)fromDate:historyDate];
NSInteger year = [weekdayComponents year];
NSInteger month = [weekdayComponents month];
NSInteger day = [weekdayComponents day];
NSDateComponents *timeZoneComps=[[NSDateComponents alloc] init];
[timeZoneComps setYear:year];
[timeZoneComps setMonth:month];
[timeZoneComps setDay:day];
[timeZoneComps setHour:00];
[timeZoneComps setMinute:00];
[timeZoneComps setSecond:01];
NSDate *convertedHistoryDate =[_gregorian dateFromComponents:timeZoneComps];
}
--我正在添加一个断点,并在执行在断点停止时进行一些检查。
现在,在服务器上,字符串是8-7月-2014,如果我鼠标悬停,我看到的日期是2014-07-08 : 05:30:00 IST,如果我点击信息,我得到了2014-07-08 00:00:00 +0000,
其次,如果我将NSCalendar和dateformatter的时区更改为本地时区,如果我检查了这个2014-07-08 : 00:00:00 IST和内部信息,我得到了2014-07-07 18:30 +0000。
所以我不理解这两件事。我还想知道,每当我从服务器得到日期,时区重要吗?它应该是什么时区?
因为我的用户可以在任何时区?因此,当他们同步数据时,他们应该得到服务器上的任何日期。我的意思是,如果2014年7月8日出现在服务器上,那么,如果美国的用户正在同步,它不应该使它成为7-7月-2014年,它应该保持8 -Jul -2014只。
问候兰吉特
发布于 2014-07-08 12:44:23
关于日期,它们实际上是用不同的时区表示的。
2014-07-08 05:30:00 IST/+05:30
2014-07-08 00:00:00 +0000
2014-07-08 00:00:00 IST/+05:30
2014-07-07 18:30:00 +0000
您需要在将日期转换为字符串时将格式化程序时区设置为正确,而visa则相反.
[inputDateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];//server timezone
[outputDateFormatter setTimeZone:[NSTimeZone systemTimeZone]];//user's timezone
https://stackoverflow.com/questions/24631906
复制相似问题