This question already has an answer here:
NSDateFormatter and Time Zone issue?
(1 answer)
Closed 8 years ago.
-(NSTimeInterval)convertStringToDate:(NSString *) date {
NSString *dateString = date;
NSLog(#"dateString = %#", dateString);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy hh:mm a"];
[dateFormatter setLocale:[NSLocale currentLocale]];
NSDate *date1 = [[NSDate alloc] init];
date1 = [dateFormatter dateFromString:dateString];
NSLog(#"dateFromString = %#", date1);
NSString *displayDate = [dateFormatter stringFromDate:date1];
NSLog(#"displayDate = %#", displayDate);
return [date1 timeIntervalSince1970];
}
Why I am getting NSTimeInterval with wrong timezone?
You need to read up on the internal representation of NSDates. An NSDate is saved as the number seconds since midnight on 1 Jan, 1984 GMT (The Mac OS X "epoch date") . It represents an instant in time anywhere on the earth, but using a date in GMT as it's "zero date". To display it, you need to convert it to your local time zone.
NSDate has a couple of methods to convert a date to a number: timeIntervalSince1970, which converts an NSDate to the internet standard, which is the number of seconds since Midnight 1 Jan 1970 (The UNIX "epoch date"), and timeIntervalSinceReferenceDate, which converts to the number seconds since the Mac Epoch date.
If you display a date in NSLog:
NSLog(#"Date = %#", someNSDate);
It will be displayed in GMT.
Honestly, it's unclear what you're asking and my best guess is that you just don't understand the classes at play. I've annotated your code in the hope of aiding your comprehension.
Key point: NSDate does not have a time zone. It's an opaque time stamp.
-(NSTimeInterval)convertStringToDate:(NSString *) date {
// log the input string
NSString *dateString = date;
NSLog(#"dateString = %#", dateString);
// create an object that can apply a locale and a time zone in order to
// convert an NSDate to an NSString and vice versa
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy hh:mm a"];
[dateFormatter setLocale:[NSLocale currentLocale]];
// get a date that represents exactly now, for no reason as it's about
// to be thrown away
NSDate *date1 = [[NSDate alloc] init];
// convert to the NSDate that represents the given string.
date1 = [dateFormatter dateFromString:dateString];
// log the converted date. BECAUSE NSDATE DOES NOT HAVE A TIME ZONE,
// it will arbitrarily be displayed in UTC. Because it has to be
// displayed in something
NSLog(#"dateFromString = %#", date1);
// convert date1 back into a printable date; this will again apply
// a time zone and locale
NSString *displayDate = [dateFormatter stringFromDate:date1];
NSLog(#"displayDate = %#", displayDate);
// query the date for "The interval between the date object and
// January 1, 1970 at 12:00 a.m. GMT."; return that
return [date1 timeIntervalSince1970];
}
Related
This question already has answers here:
Getting date from [NSDate date] off by a few hours
(3 answers)
Closed 8 years ago.
- (void) dateConverter{
NSString *string = [NSString stringWithFormat:#"%# %#", [[self dates]objectAtIndex:0], [times objectAtIndex:0]]; // string = 01-10-2014 11:36 AM;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy hh:mm a"];
[dateFormatter setLocale:[NSLocale currentLocale]];
NSDate *date = [[NSDate alloc] init];
date = [dateFormatter dateFromString:string];
NSLog(#"dateFromString = %#", date); // 2014-10-01 18:36:00 +0000
NSTimeInterval timeInterval = [date timeIntervalSince1970];
NSLog(#"dateFromString = %f", timeInterval); // 1412188560.000000
}
I am converting the string to actual date object, but I am getting different behavior
string = 01-10-2014 11:36 AM
is actual value I am trying to convert but getting this
2014-10-01 18:36:00 +0000
what is wrong with it?
The problem is a display issue.
You are using the default date formatter to print the date (NSLog used the description method).
The time is displayed in UTC (GMT) and it looks like you are in timezone -0700. The time is being displayed in timezone offset 0000.
The date/time in the system is based on the GMT time, that way times can be compared across timezones and everywhere on Earth the time is the same in the system at the same time.
Use a date formatter to get the date/time in the format you want.
Example code:
NSString *dateString = #"01-10-2014 11:36 AM";
NSLog(#"dateString = %#", dateString);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy hh:mm a"];
[dateFormatter setLocale:[NSLocale currentLocale]];
NSDate *date = [[NSDate alloc] init];
date = [dateFormatter dateFromString:dateString];
NSLog(#"dateFromString = %#", date);
NSString *displayDate = [dateFormatter stringFromDate:date];
NSLog(#"displayDate = %#", displayDate);
Output:
dateString = 01-10-2014 11:36 AM
dateFromString = 2014-10-01 15:36:00 +0000
displayDate = 01-10-2014 11:36 AM
Note: You can supply your own date format to get exactly the format what you want.
This question already has answers here:
Convert NSDate to NSString
(19 answers)
Closed 8 years ago.
I have an NSDate Object which is in 12 hour format like 2014-09-16 04:40:05 pm +0000.
I want to convert this into 24 hour format and want to get back an NSDate object like 2014-09-16 16:40:05 +0000.
Can some one guide me in doing that.
So i want some method like :
-(NSDate *) get24HourFormat:(NSDate *) date{
return date object;
}
Simple use this:
NSDateFormatter *dateformate=[[NSDateFormatter alloc]init];
dateformate.dateFormat = #"HH:mm a"; // Date formater
NSString *timeString = [dateformate stringFromDate:[NSDate date]]; // Convert date to string
NSLog(#"timeString :%#",timeString);
Logic: Simply convert date format hh:mm to HH:mm
There seems to be a deep misunderstanding here what NSDate is and does.
An NSDate object is a point in time in UTC. It doesn't have a time zone. It doesn't have a format. It has nothing. You can't change its format, it doesn't even make any sense.
What you can do is to use an NSDateFormatter to convert the NSDate to a string. By default, NSDateFormatter uses your local time zone, which means for most people that the result will be different from the result that NSLog would show for an NSDate. In the NSDateFormatter, you can use whatever settings you want.
Usually you would respect how the user set up his date formatting and not change it for anything that is visible to the user. As a user, if I had set up my device to show days in 12 hour format, I'd be very annoyed if your application worked differently.
try this..
-(NSString *)changeformate_string24hr:(NSString *)date
{
NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setTimeZone:[NSTimeZone systemTimeZone]];
[df setDateFormat:#"MM/dd/yyyy hh:mm:ss a"];
NSDate* wakeTime = [df dateFromString:date];
[df setDateFormat:#"MM/dd/yyyy HH:mm:ss"];
return [df stringFromDate:wakeTime];
}
-(NSString *)changeformate_string12hr:(NSString *)date
{
NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setTimeZone:[NSTimeZone systemTimeZone]];
[df setDateFormat:#"MM/dd/yyyy HH:mm:ss"];
NSDate* wakeTime = [df dateFromString:date];
[df setDateFormat:#"MM/dd/yyyy hh:mm:ss a"];
return [df stringFromDate:wakeTime];
}
I have this string date:
2014-04-21T07:55:13Z
when I convert that to NSDate I have the hour like 6:55... 1 hours less. WHY?
This is the code I am using to convert:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSDate *newDate = [dateFormatter dateFromString:dateStr];
newDate is now 2014-04-21 06:55:13 +0000 !!!???
what is wrong?
NOTE: That one hour less would make sense if the date was my local time (GMT+1) being converted to GMT. But if that Z is zero offset ( = GMT) the date is already GMT.
I don't think your code is wrong. using this code:-
NSString *dateStr = #"2014-04-21T07:55:13Z";
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSDate *date = [dateFormat dateFromString:dateStr];
NSLog(#" date log %#",date); //2014-04-21 02:25:13 +0000 output
// Convert date object to desired output format
[dateFormat setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
dateStr = [dateFormat stringFromDate:date];
NSLog(#"string %#",dateStr); //2014-04-21T07:55:13Z output
but NSLog of NSDATE is not output correct according to this NSDate Format outputting wrong date so your code is right.
The NSDate doesn't know anything about formatting (just date information), and the NSDateFormatter doesnt really know anything about dates, just how to format them. So you have to use methods like -stringFromDate: for know that is current or not to actually format the date for pretty human-readable display.
NSLog(#" date is %#",[dateFormat stringFromDate:date]);
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.
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.
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);
}
See the stringFromDate Method in the dateformatter. You pass in an NSDateand it converts to the specified format.
UPDATE: Here is how you set the current time zone [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html
We are building an app which requires the storage of a date for an entry on the device, the app will be international so we hit two dilema's / challenges.
User Preferences
If the user chooses the 12 hour rahter than 24 hour format we are returned from [NSDate date] a date like this 2012-07-17 11:26:03 AM which for sorting in a SQLite database is less than optimal as we cannot store it as a date.
User Locale
Typically this is ok however here in blighty we have a wonderfult thing called british summertime. which adds one hour every October 25th - 30th in a cycle and removes one hour every March 25 - 31th in a cycle so if no adjustment is made for 8 months of the year the time is one hour behind.
What I need to achieve is a consistent date formatted like this: 2012-07-17 11:26:03 no matter where the device is located and also taking into account where GMT+1 comes into place.
Any help would be awesome.
EDIT*
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd'T'HH:mm";
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:#"GMT+01:00"];
[dateFormatter setTimeZone:gmt];
NSString *timeStamp = [dateFormatter stringFromDate:[NSDate date]];
NSDate *localDate = [dateFormatter dateFromString:timeStamp];
NSLocale* currentLocale = [NSLocale currentLocale];
NSString* countryCode = [currentLocale objectForKey:NSLocaleCountryCode];
NSLog(#"Country Code: %#", countryCode);
NSLog(#"Current Loacle: %#", currentLocale);
if(([countryCode isEqualToString: #"GB"])){
NSDate *mydate = [NSDate date];
NSDate *fiddlyFoo = [mydate dateByAddingTimeInterval:3600];
NSLog(#"Print GMT +1 %#",fiddlyFoo);
} else {
NSLog(#"Print GMT Local %#",localDate);
}
I'm doing something like this now. Note that NSDate "knows" about the current timezone and daylight savings time etc. So you just need to get the GMT version of the time in a sortable representation. I'd suggest RFC 3339 but you can use variations on it per your needs:
This code:
NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
// Create a local date for London, for testing purposes
NSDateComponents *comps = [NSDateComponents new];
[comps setTimeZone:[NSTimeZone timeZoneWithName:#"Europe/London"]];
[comps setDay:1];
[comps setMonth:7];
[comps setYear:2012];
[comps setHour:14];
NSDate *date = [gregorian dateFromComponents:comps];
// Just want to show this date is 2PM in London July 1st
NSDateFormatter *curFormat = [NSDateFormatter new];
[curFormat setDateStyle:NSDateFormatterFullStyle];
[curFormat setTimeStyle:NSDateFormatterFullStyle];
NSLog(#"Reference date is good no: %#", [curFormat stringFromDate:date]);
// So now we get the date as a rfc3339 string, referenced to GMT
NSString *timeString;
{
NSDateFormatter *rfc3339 = [NSDateFormatter new];
[rfc3339 setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
rfc3339.timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
timeString = [rfc3339 stringFromDate:date];
}
// referenced to UTC (sortable with any other time), can save in SQL DB etc
NSLog(#"Date as rfc3339 string: %#", timeString);
// Now lets convert it back into a BST time
NSDate *newDate;
{
NSDateFormatter *rfc3339 = [NSDateFormatter new];
[rfc3339 setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
rfc3339.timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
newDate = [rfc3339 dateFromString:timeString];
// we want to show this as a string 2012-07-17 11:26:03
NSDateFormatter *newFormatter = [NSDateFormatter new];
[newFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"]; // local time
[newFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"Europe/London"]];
NSLog(#"Local string using 24 hour clock: %#", [newFormatter stringFromDate:newDate]);
}
Generates this output, which I believe is what you want:
TimeTester[58558:f803] Reference date is good no: Sunday, July 1, 2012 9:00:00 AM Eastern Daylight Time
TimeTester[58558:f803] Date as rfc3339 string: 2012-07-01T13:00:00Z
TimeTester[58558:f803] Local string using 24 hour clock: 2012-07-01 14:00:00