Reputation: 17920
I am trying to convert my device current time into Zone (America/New_york
)
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"America/New_York"]];
NSDate *start = [NSDate date];
start
now has the device current time in IST
. How can I convert it into zone 'America'
I planned to do the below
start = [dateFormatter dateFromString:<start date String>];
A Day is categorised into 3 divisions based on a time period.
Say 08:00 - 15:00 AS PHASE1
15:00 - 17:00 AS PHASE2
17:00 - 20:00 AS PHASE3
20:00 - 08:00 AS TRANSITION PHASE and can be ignored.
Am just taking device's date and append the time string to identify in which phase it is.
Example: Indian Time is 05-FEB-2014 01:25 AM (Device Date)
Considering 15:00
as first cutoff.. I append the '05-FEB-2014
' to 15:00
and digest it as American timezone.. Which resolves and gives me 06-FEB-2014 02:30 IST
(Cut off Date).. So the difference between the both days goes greater than one day!
My expected result could be take device time also in American Timezone and compare with the compare with the nearest cut off time.
Upvotes: 2
Views: 4563
Reputation: 6614
Date of new york :
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"America/New_York"];
[dateFormatter setTimeZone:timeZone];
NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"Date : %@", dateString);
Date of all zones :
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSArray *timeZoneNames = [NSTimeZone knownTimeZoneNames];
for (NSString *name in timeZoneNames) {
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:name];
[dateFormatter setTimeZone:timeZone];
NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"timeZone abbreviation : %@\nName : \"%@\"\nDate : %@\n\n", [timeZone abbreviation], name, dateString);
}
Upvotes: 5
Reputation: 3765
See the stringFromDate
Method in the dateformatter. You pass in an NSDate
and it converts to the specified format.
UPDATE: Here is how you set the current time zone [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
Upvotes: 1
Reputation: 70946
NSDate
does not have a time zone. It's a single time reference that's valid anywhere. It's basically just an object wrapper for NSTimeInterval
-- all it stores is the number of seconds since a reference date. Time zones only apply when converting to/from user-visible strings.
You can get a user-visible string from your date formatter as
NSString *localizedDateString = [dateFormatter stringFromDate:start];
But converting NSDate
to a particular time zone is not a meaningful goal. There's no time zone on NSDate
, so it's not a conversion that can be applied.
Upvotes: 6