iOS7 how to get current time and date based on specified timezone? - ios

iOS Programming: I just want to let iOS7 get the "America/Chicago" current date and time.
I searched a lot on Internet, but there are a lot of different solutions. I tried several solutions, but they do not work.

You can use the NSCalendar and NSTimezone classes. The following code segment demonstrates retrieving the current hour and minute. Extending it to retrieve other date components is straight-forward -
long hour;
long minute;
NSCalendar *cal=[NSCalendar currentCalendar];
NSDate *now=[NSDate date];
NSTimeZone *tz=[NSTimeZone timeZoneWithName:#"America/Chicago"];
[cal setTimeZone:tz];
NSDateComponents *comp=[cal components:NSHourCalendarUnit|NSMinuteCalendarUnit fromDate:now];
hour=[comp hour];
min=[comp minute];

You can use this method,
- (NSDate *) getCountryDateWithTimeZone:(NSString *)zone
{
NSDate *now = [NSDate date];
NSTimeZone *szone = [NSTimeZone timeZoneWithName:zone];
NSInteger sourceGMTOffset = [szone secondsFromGMTForDate:now];
NSTimeInterval interval = sourceGMTOffset;
NSDate *destinationDate = [NSDate dateWithTimeInterval:interval sinceDate:now];
return destinationDate;
}
And,
[self getCountryDateWithTimeZone:#"America/Chicago"];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSString *firstDate = #"2014-06-05 12:55:00";
NSDate *date=[dateFormatter dateFromString:firstDate];
NSDate *currentDate = [NSDate date];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:date toDate:currentDate options:0];
NSLog(#"The difference between from date and to date is %d days and %d hours and %d minute and %d second",components.day,components.hour,components.minute,components.second);
Output:
DateBookApp[1179:70b] The difference between from date and to date is 0 days and 22 hours and 57 minute and 12 Second

Related

About NSDateComponents:Why I can't get the correct day component?

I want get day component from localDate, [NSDate localDate] just transform the GMT into local time.
NSDate *localDate=[NSDate localDate];
// localDate:2017-03-13 18:35:35 +0000
NSLog(#"localDate:%#",localDate);
NSInteger dayComponentLocal=[[NSCalendar currentCalendar] component:(NSCalendarUnitDay) fromDate:localDate];
NSLog(#"dayComponentLocal:%ld",(long)dayComponentLocal);
But why the output is 14?
There is the implement of [NSDate localDate]:
NSDate *date=[NSDate date];
NSTimeZone *zone=[NSTimeZone systemTimeZone];
NSInteger interval=[zone secondsFromGMTForDate:date];
NSDate *localDate=[date dateByAddingTimeInterval:interval];
return localDate;
And there is another error when I want to get the first weekday of current month, there is the code:
NSDate *date=[NSDate localDate];
NSInteger dayComponents=[[NSCalendar currentCalendar] component:(NSCalendarUnitDay) fromDate:date];
NSInteger secondsInADay=24*60*60;
NSDate *firstDay=[date dateByAddingTimeInterval:-((dayComponents-1)*secondsInADay)];
NSInteger weekdayComponent=[[NSCalendar currentCalendar] component:(NSCalendarUnitWeekday) fromDate:firstDay];
NSLog(#"firstDay:%#",firstDay);
NSLog(#"weekday Of firstDay:%ld",weekdayComponent);
due to the wrong dayComponents, I subtract one more day from 'localDate' and get the wrong firstDay '2017-02-28 20:09:32 +0000' rather than the correct answer '2017-03-01 20:09:32 +0000'. 2-28 is Tuesday, but I get 4, which means Wednesday,
Why?
You are adding the number of seconds from GMT in localDate. As your time zone is positive you need to subtract the seconds (-interval) to get UTC.
By the way never ever use 86400 for date math. Use the date calculation methods of NSCalendar
For example you get the first weekday of the current month with
NSCalendar *calendar = [NSCalendar currentCalendar];
// calendar.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
NSDate *startDate;
NSTimeInterval interval;
[calendar rangeOfUnit:NSCalendarUnitMonth startDate:&startDate interval:&interval forDate:[NSDate date]];
NSInteger weekday = [calendar component:NSCalendarUnitWeekday fromDate:startDate];
NSLog(#"%ld", weekday);
To get the date related to UTC uncomment the time zone line.
Remove the time components from the date before taking the day component.
Try this code
NSDate *localDate=[NSDate localDate];
// localDate:2017-03-13 18:35:35 +0000
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSString *strDate = [dateFormatter stringFromDate: localDate];
localDate = [dateFormatter dateFromString: strDate];
NSInteger dayComponentLocal=[[NSCalendar currentCalendar] component:(NSCalendarUnitDay) fromDate:localDate];
NSLog(#"dayComponentLocal:%ld",(long)dayComponentLocal);
You will get output 13. This occur maybe because of difference in time zone

How to get days in a week from today in objective c

I am trying to get the days of a week in reference to their date.
Ex.: 14th October is a Wednesday.
I am creating a collection view cell and displaying the date as follows.
In the 14th cell it would display Wednesday, but how to get the next day as Thursday, then Friday...and so on.
I have got todays date and which day it is as follows,
day = [components day];
week = [components month];
year = [components year];
weekday = [components weekday];
NSString *string = [NSString stringWithFormat:#"%ld.%ld.%ld", (long)day, (long)week, (long)year];
NSLog(#"%#",string);
NSDate *todayDate = [NSDate date]; // get today date
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"EEEE"];
NSString *convertedDateString = [dateFormatter stringFromDate:todayDate];// here convert date in
NSLog(#"Today formatted date is %#",convertedDateString);
And i have found this method online, which returns the days in string when you pass the integer, but i am having trouble in this too, not understanding which integer to pass every time so I get different strings.
static inline NSString *stringFromWeekday(int weekday){
static NSString *strings[] = {
#"Sunday",
#"Monday",
#"Tuesday",
#"Wednesday",
#"Thursday",
#"Friday",
#"Saturday",
};
return strings[weekday];
}
You already got everything in place. You should be getting the correct day name in the convertedDateString string. You just have to add 24 hours to your todayDate object and use the dateformatter again to get the next day.
NSDate *todayDate = [NSDate date]; // get today date
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"EEEE"];
NSString *convertedDateString = [dateFormatter stringFromDate:todayDate];// here convert date in
You can get the next day like this.
NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:(NSDayCalendarUnit | NSMonthCalenderUnit | NSYearCalenderUnit | NSWeekdayCalendarUnit) fromDate:today];
[dateComponents setDay:dateComponents.day+1];
NSDate *nextDay = [dateComponents date];
// Get the day by following same approach in the top
You will get days in a week from today using below code.
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents =
[gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:today];
NSInteger day = [weekdayComponents day];
NSInteger weekday = [weekdayComponents weekday];

How to get and convert back user's birthdate to/from a NSTimeInterval?

Suppose, my birthdate is (mon/day/year) 10-05-1932 (as NSDate), how to convert this to NSTimeInterval.
Again, how to convert back that NSTimeInterval to NSDate back?
I tried using different methods of NSDate but haven't succeed yet.
What I'm doing?
NSString *strdate = #"10-05-1932";
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"MM-dd-yyyy"];
NSDate *date = [df dateFromString:strdate];
NSLog(#"%.f", -[date timeIntervalSinceNow]);
This logs 2616605071 (as on 4th September 2015 at 16:21) – When I checked it with the site like this it gives me wrong date.
NSTimeInterval timeInterval = date.timeIntervalSinceReferenceDate;
NSDate *anotherDate = [NSDate dateWithTimeIntervalSinceReferenceDate: timeInterval];
Try the code below. date and anotherDate will be identical.
NSCalendar *calendar = [NSCalendar currentCalendar];
calendar.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:10];
[components setMonth:5];
[components setYear:1934];
NSDate *date = [calendar dateFromComponents:components];
NSLog(#"%#", date);
NSTimeInterval timeInterval = [date timeIntervalSinceReferenceDate];
NSDate *anotherDate = [NSDate dateWithTimeIntervalSinceReferenceDate:timeInterval];
NSLog(#"%#", anotherDate);
UPDATE:
It's incorrect because you get timestamp (time interval) from that website which use UNIX timestamp. Also, it's incorrect because you use timeIntervalSinceNow which will likely change every time you call the method because it's relative to the current time. If you want the date/time interval that compatible with that website. Use:
NSTimeInterval timeInterval = date.timeIntervalSince1970;
NSDate *anotherDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
You can copy the timeInterval from the code above (-1188000000) and paste it on the website and it will give you a correct date.
Internally, NSDate store time interval relative to reference date (Jan 1st, 2001). The website you mentioned is UNIX timestamp that relative to Jan 1st, 1970.
This is just worked!
NSString *strdate = #"10-05-1932";
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"MM-dd-yyyy"];
NSDate *date = [df dateFromString:strdate];
NSLog(#"%#",date);
NSTimeInterval interval = [date timeIntervalSince1970];
NSLog(#"%f", interval);
NSDate *date2 = [NSDate dateWithTimeIntervalSince1970:interval];
NSLog(#"%#",date2);
Thanks to #sikhapol

Getting unexpected output from NSDateComponents

After comparing two dates (currentDate and _timerStartDate) I get the following output
nstimeinterval: 88.998212
2014-05-14 14:07:08.284 currentDate: 14-05-2014 14:07:08
2014-05-14 14:07:08.284 stopDate: 14-05-2014 14:05:39
2014-05-14 14:07:08.284 hour: 10
This is correct and expected. However when I break timerDate down I get 10 hours from the NSLog...I'm expecting zero. What am I doing wrong?
Here is my code:
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:_timerStartDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"mm:ss"];
NSString *timeString=[dateFormatter stringFromDate:timerDate];
NSLog(#"nstimeinterval: %f", timeInterval);
[dateFormatter setDateFormat:#"dd-MM-yyyy HH:mm:ss"];
NSLog(#"currentDate: %#", [dateFormatter stringFromDate:currentDate]);
NSLog(#"stopDate: %#", [dateFormatter stringFromDate:_timerStartDate]);
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components: ( NSHourCalendarUnit | NSYearCalendarUnit) fromDate:timerDate];
NSLog(#"year: %li", (long)components.year);
NSLog(#"timer: %#", timeString);
timerTicksForCounter = timeString;
NSLog(#"hour: %li", (long)components.hour);
What is it you're actually trying to accomplish? To populate an NSDateComponents with the time elapsed between two dates? In that case, you probably want -[NSCalendar components:fromDate:toDate:options:], with the from-date being your start, and the to-date being the current date when you stop. In the mean time, you seem to be doing a lot of complicated and possibly unnecessary mashing of dates together.

NSDate subtracting trouble

so in my app I want to subtract two dates. The first date is set date and the second one is the current date. So i tried this code:
NSString *setDateString = [NSString stringWithFormat:#"12:30"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSDate *setDate = [dateFormatter dateFromString:setDateString];
NSTimeInterval interval = [[NSDate date] timeIntervalSinceDate:setDate];
But it counts the interval from 1970. But I need from the current day. Can anyone help?
I assume you want the difference between now and 1230 hrs of today. This can be done by
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components =[gregorian components:(NSDayCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit) fromDate:today];
[components setHour:12];
[components setMinute:30];
[components setSecond:0];
NSDate *setDate=[gregorian dateFromComponents:components];
NSTimeInterval interval = [[NSDate date] timeIntervalSinceDate:setDate];
[gregorian release];
The reason it doesn't work for you is you've not given the format correctly. Alternatively, you can describe it correctly in setDateString by specifying all the components rather than just hour and minute.

Resources