I'm using Parse.com to store some values:
These are GMT values. How do I convert these to the device's current time zone and get NSDate as a result?
NSDate is always represented in GMT. It's just how you represent it that may change.
If you want to print the date to label.text, then convert it to a string using NSDateFormatter and [NSTimeZone localTimeZone], as follows:
NSString *gmtDateString = #"08/12/2013 21:01";
NSDateFormatter *df = [NSDateFormatter new];
[df setDateFormat:#"dd/MM/yyyy HH:mm"];
//Create the date assuming the given string is in GMT
df.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
NSDate *date = [df dateFromString:gmtDateString];
//Create a date string in the local timezone
df.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:[NSTimeZone localTimeZone].secondsFromGMT];
NSString *localDateString = [df stringFromDate:date];
NSLog(#"date = %#", localDateString);
// My local timezone is: Europe/London (GMT+01:00) offset 3600 (Daylight)
// prints out: date = 08/12/2013 22:01
The easiest method I've found is this:
NSDate *someDateInUTC = …;
NSTimeInterval timeZoneSeconds = [[NSTimeZone localTimeZone] secondsFromGMT];
NSDate *dateInLocalTimezone = [someDateInUTC dateByAddingTimeInterval:timeZoneSeconds];
This is a very clean way to change the NSDate to a local time zone date
extension NSDate {
func toLocalTime() -> NSDate {
let timeZone = NSTimeZone.local
let seconds : TimeInterval = Double(timeZone.secondsFromGMT(for:self as Date))
let localDate = NSDate(timeInterval: seconds, since: self as Date)
return localDate
}
}
taken from https://agilewarrior.wordpress.com/2012/06/27/how-to-convert-nsdate-to-different-time-zones/
Creating an Xcode test case like the following may help us remember the rules "forever":
- (void)test2015_05_23_07_07_07_Toronto {
NSString *utcDateString = #"2015_05_23 12:07:07";
NSDateFormatter *dateFormatter = [NSDateFormatter new];
dateFormatter.dateFormat = #"yyyy_MM_dd HH:mm:ss";
dateFormatter.timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
NSDate *date2015_05_23_12_07_07_UTC = [dateFormatter dateFromString:utcDateString];
XCTAssertTrue([date2015_05_23_12_07_07_UTC.description isEqualToString:#"2015-05-23 12:07:07 +0000"]);
dateFormatter.timeZone = [NSTimeZone timeZoneWithName:#"EST"];
NSString *torontoDateString = [dateFormatter stringFromDate:date2015_05_23_12_07_07_UTC];
XCTAssertTrue([torontoDateString isEqualToString:#"2015_05_23 07:07:07"]);
// change format to add ZZZ
dateFormatter.dateFormat = #"yyyy_MM_dd HH:mm:ss ZZZ";
torontoDateString = [dateFormatter stringFromDate:date2015_05_23_12_07_07_UTC];
XCTAssertTrue([torontoDateString isEqualToString:#"2015_05_23 07:07:07 -0500"]);
XCTAssertEqual(1432382827, [date2015_05_23_12_07_07_UTC timeIntervalSince1970]);
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
calendar.timeZone = [NSTimeZone timeZoneWithName:#"EST"];
NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:date2015_05_23_12_07_07_UTC];
XCTAssertEqual(2015, components.year);
XCTAssertEqual(5, components.month);
XCTAssertEqual(23, components.day);
XCTAssertEqual(7, components.hour);
XCTAssertEqual(7, components.minute);
XCTAssertEqual(7, components.second);
}
You could use a NSDateFormatter to achieve this result.
NSString *dateAsString = #"08/07/2013 04:06";
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"dd/MM/yyyy HH:mm"];
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
[df setTimeZone:gmt];
NSDate *myDate = [df dateFromString: dateAsString];
NSLog(#"date: %#", myDate);
There are many answers to this question but I would recommend this one:
Convert GMT NSDate to device's current Time Zone
NSString *dateStr = #"2012-07-16 07:33:01";
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [dateFormatter1 dateFromString:dateStr];
NSLog(#"date : %#",date);
NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone]; // <- Local time zone
NSTimeZone *utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"UTC"];
NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:date1];
NSInteger gmtOffset = [utcTimeZone secondsFromGMTForDate:date1];
NSTimeInterval gmtInterval = currentGMTOffset - gmtOffset;
NSDate *destinationDate = [[[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:date1] autorelease];
NSDateFormatter *dateFormatters = [[NSDateFormatter alloc] init];
[dateFormatters setDateFormat:#"dd-MMM-yyyy hh:mm"];
[dateFormatters setDateStyle:NSDateFormatterShortStyle];
[dateFormatters setTimeStyle:NSDateFormatterShortStyle];
[dateFormatters setDoesRelativeDateFormatting:YES];
[dateFormatters setTimeZone:[NSTimeZone systemTimeZone]];
dateStr = [dateFormatters stringFromDate: destinationDate];
NSLog(#"DateString : %#", dateStr);
Related
I am facing problem while converting given date into system time zone in iOS.
Source date: 2013-03-18 03:54:18 // its in AM format
Destination date should be : 2013-03-18 03:30:15 //its in PM format.
How can I get this??
I have tried below code but getting wrong data and difference too.
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = #"yyyy-MM-dd HH:mm:ss";
NSLog(#"Post date::%#",postDate);
NSDate *utc = [fmt dateFromString:postDate];
fmt.timeZone = [NSTimeZone systemTimeZone];
NSString *local = [fmt stringFromDate:utc];
NSLog(#" local %#", local);
NSDate *date1 = [NSDate date];
NSString *currentDateString = [fmt stringFromDate:date1];
NSDate *currentDate = [fmt dateFromString:currentDateString];
NSUInteger flags = NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit;
NSDateComponents *difference = [[NSCalendar currentCalendar] components:flags fromDate:utc toDate:currentDate options:0];
NSLog(#"difference::%d",[difference day]);
NSLog(#"difference::%d",[difference hour]);
NSLog(#"difference::%d",[difference minute]);
EDIT: Outputs
Post date::2013-03-18 03:20:09
local 2013-03-18 03:20:09
difference::0
difference::13
difference::2
Replace your code from...
fmt.timeZone = [NSTimeZone systemTimeZone];
as like this
fmt.timeZone = [NSTimeZone localTimeZone];
This will works for you...
NSString *openingHour = #"15:05:35 ";
NSDateFormatter *workingHoursFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
[workingHoursFormatter setTimeZone:timeZone];
[workingHoursFormatter setDateFormat:#"HH:mm"];
NSDate *openingTime = [workingHoursFormatter dateFromString:openingHour];
Can you try the above code it works for me , alter the date format to your need
So I have the following code:
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MM/dd/yyyy hh:mma"];
NSString *dateString = [dateFormat stringFromDate:self.firstUsed];
NSLog(#"FIRST USED %# %f", dateString, [[NSDate date] timeIntervalSinceDate:self.firstUsed]);
FIRST USED 06/15/2012 10:42PM 716.087895
The thing that confuse me is that when I put in 173.755023 it doesn't translate back to June 15th 2012 10:42. How is this possible? I think the correct number should be 1339714440
Try this :
NSDate* referenceDate = [NSDate dateWithTimeIntervalSince1970: 0];
NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:#"GMT"];
int offset = [timeZone secondsFromGMTForDate: referenceDate];
int unix_timestamp = [curdate timeIntervalSince1970];
int Timestamp = unix_timestamp - offset;
Please write down Following Code :
NSDateFormatter *dtFormatAppointment = [[NSDateFormatter alloc] init];
[dtFormatAppointment setDateFormat:#"MM/dd/yyyy hh:mm a"];
NSString *dateString = [dateFormat stringFromDate:self.firstUsed];
NSTimeInterval time = [dateString timeIntervalSince1970];
NSLog(#"FIRST USED %# %.f", dateString, time);
this code is working for you.
I have the following date:
2011-10-20T01:10:50Z
I would like it to be formatted to
"M/d/yy 'at' h:mma"
Here is my code:
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
//The Z at the end of your string represents Zulu which is UTC
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"]];
[dateFormatter setDateFormat:#"yyyy-dd-MM'T'HH:mm:ss'Z'"];
NSDate* newTime = [dateFormatter dateFromString:[message valueForKey:#"created_at"]];
//Add the following line to display the time in the local time zone
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
[dateFormatter setDateFormat:#"M/d/yy 'at' h:mma"];
NSString* finalTime = [dateFormatter stringFromDate:newTime];
[dateFormatter release];
NSLog(#"%#", finalTime);
Unfortunately the finalTime is NULL here.
You have dd-MM backwards. You have 10 for dd and 20 MM. There is no month 20.
2011-10-20T01:10:50Z
#"yyyy-dd-MM'T'HH:mm:ss'Z'"
Because of that, the newTime was null and the finalTime was null.
Here's with the fix. This:
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
//The Z at the end of your string represents Zulu which is UTC
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"]];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSDate* newTime = [dateFormatter dateFromString:#"2011-10-20T01:10:50Z"];
NSLog(#"original time: %#", newTime);
//Add the following line to display the time in the local time zone
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
[dateFormatter setDateFormat:#"M/d/yy 'at' h:mma"];
NSString* finalTime = [dateFormatter stringFromDate:newTime];
NSLog(#"%#", finalTime);
[dateFormatter release];
Outputs:
2011-10-19 22:05:15.107 Craplet[4231:707] original time: 2011-10-20 01:10:50 +0000
2011-10-19 22:05:15.116 Craplet[4231:707] 10/19/11 at 9:10PM
This technical note helped me resolve the same issue: https://developer.apple.com/library/ios/qa/qa1480/_index.html
In a nutshell, you need to set 3 things on NSDateFormatter:
Locale
TimeZone
DateFormat
code sample:
NSLocale *locale = [NSLocale localeWithLocaleIdentifier:#"en_US_POSIX"];
[dateFormatter setLocale:locale];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
[dateFormatter setDateFormat:#"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'"];
NSDate *date = [dateFormatter dateFromString:#"2014-10-23T01:10:50.000Z"];
I was using NSDateFormatter to successfully parse UTC strings to NSDate by only setting time zone and date format. When it suddenly stopped working I found this tech note and added setLocal: which resolved the issue for me.
Because Swift:
let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
let dateHopefully = dateFormatter.dateFromString("2016-07-29T17:15:02Z")
dateFormatter.timeZone = NSTimeZone.systemTimeZone()
dateFormatter.dateFormat = "M/d/yy 'at' h:mma"
let lastTime = dateFormatter.stringFromDate(dateHopefully!)
print("Here is the hopeful date \(dateHopefully) and here is the lastTime \(lastTime)")
How will I compare current time [NSDate date] with fixed time 05:00:00 PM.
That 05:00 PM is already passed or not. I just need BOOL check for this.
- (BOOL)past5pm
{
NSCalendar *gregorianCalender = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *components = [gregorianCalender components:NSHourCalendarUnit fromDate:[NSDate date]];
if([components hour] >= 17) // NSDateComponents uses the 24 hours format in which 17 is 5pm
return YES;
return NO;
}
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"HH.mm"];
NSDate *currentDate = [NSDate date];
NSString *curDate = [dateFormatter stringFromDate:currentDate];
if ([curDate doubleValue] >= 17.00)
{
//set your bool
}
Try this
NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"hh:mm:ss a"];
NSDate* date = [NSDate date];
//Get the string date
NSString* str = [dateFormatter stringFromDate:date];
NSDate *firstDate = [dateFormatter dateFromString:#"05:00:00 PM"];
NSDate *secondDate = [dateFormatter dateFromString:str];
NSTimeInterval timeDifference = [secondDate timeIntervalSinceDate:firstDate];
NSLog(#"Time Diff - %f",timeDifference);
You can probably use plain C style code and get the difference as an integer and then decide what you need to return from the comparison function depending on wether the difference is positive or negative. You can compare minutes this way as well. Dont forget to import time.h.
time_t now = time(NULL);
struct tm oldCTime;
localtime_r(&now, &oldCTime);
int hours = oldCTime.tm_hour;
int diff = 17-hours;
NSLog(#"Time difference is: %d.", diff);
I have two strings both are in following date format (2011-03-22).
i have to compare them and find number of days between them.
Can anyone tell me how to do this..
Please also tell me the correct method to convert them back to NSDate.
Might be a couple of errors as i just typed this, but it speaks for itself and you should get the idea.
NSString *dateStringA = #"2011-03-22";
NSString *dateStringB = #"2011-03-27";
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
df.dateFormat = #"yyyy-MM-dd";
NSDate *dateA = [df dateFromString:dateStringA];
NSDate *dateB = [df dateFromString:dateStringB];
NSDateComponents *comps = [[NSCalendar currentCalendar] components:NSDayCalendarUnit fromDate:dateA toDate:dateB options:0];
int daysBetweenDates = comps.day; //This is your days between the 2 dates
NSDate *intervalDate = [[NSCalendar currentCalendar] dateFromComponents:comps]; //This date object represents the duration between them
For string to date
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyy-MM-dd HH:mm:ss ZZZ"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:<NSString containing date>];
for date to string
NSString *date = [[NSDate date] description];