NSLog showing the previous Date - ios

I want to retrieve all the entries from core data added between two dates.I am using NSPredicate. As I am not getting the correct result I tried logging the date.It is showing the previous dates.After googling for a while I added
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; to my code.Now,Its showing correct dates but the results are still wrong.
This is the code I used.
NSDate *fromDate = [[self dateFormatter]dateFromString:self.fromDateField.text];
NSLog(#"%#",fromDate);
NSDate *toDate = [[self dateFormatter]dateFromString:self.toDateField.text];
NSLog(#"%#",toDate);
NSComparisonResult result = [fromDate compare:toDate];
switch (result) {
case NSOrderedAscending:
{
//code
}
- (NSDateFormatter *)dateFormatter
{
static NSDateFormatter *dateFormatter = nil;
if (dateFormatter == nil)
{
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
}
return dateFormatter;
}
Thanks in advance

If you log an NSDate object directly it will always display the tome in GMT/UTC timezone. you have to log the output of a date formatter.
NSLog(#"%#",[self.dateFormatter stringFromDate:toDate]);
This will take your timezone in account. Or better: the timezone of the dateformatter's calendar — what is the device default if you dont change that.

Related

Getting UTC time for any time and handling daylight saving as well

I have written a function to get UTC time string corresponding to any time string passed as an argument to function.
+(NSString *)getUTCTime:(NSString *)selectedTime
{
NSString *strFormat;
if ([self is24HourFormat:selectedTime]){
strFormat = #"HH:mm";
}
else{
strFormat = #"hh:mm a";
}
NSLocale *baseLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
NSDateFormatter *dateFormatterlocal = [[NSDateFormatter alloc] init];
[dateFormatterlocal setTimeZone:[NSTimeZone systemTimeZone]];
dateFormatterlocal.locale = baseLocale;
[dateFormatterlocal setDateFormat:strFormat];
NSDate *selectedDate = [dateFormatterlocal dateFromString:selectedTime];
NSDateFormatter *dateFormatterUTC = [[NSDateFormatter alloc] init];
[dateFormatterUTC setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
dateFormatterUTC.locale = baseLocale;
[dateFormatterUTC setDateFormat:strFormat];
NSString *utcTimeString = [dateFormatterUTC stringFromDate:selectedDate];
return utcTimeString;
}
It working fine for Mumbai, India time zone. But if i change the timezone to London, its returning me the same time that I'm passing in function argument. Currently it is UTC+1 in London. Does NSDateFormatter handle daylight saving?
You can use NSTimeZone methods as shown below for daylight saving: See NSTimeZone Class Reference
isDaylightSavingTimeForDate:// will tell you if day light saving exist for this date
daylightSavingTimeOffset // will tell you how much offset is the time for daylight saving
Use below code it returns properly day light saving with offset
var timeZone:NSTimeZone = NSTimeZone(name:"Europe/London")!
print(timeZone.daylightSavingTime) //this will return true if day light saving present
print(timeZone.daylightSavingTimeOffset/(60*60))//this will give you number of hours by which the day light saving offset should be
print("timezone: \(timeZone)")//will give you detail about timezone

Storing date and time separately in NSDate

So i am getting a string containing date and time in this format "2014-12-22T11:00:00+0500" Now in order to convert it into NSdate i am using
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ssZZZ"];
NSDate* date = [dateFormatter dateFromString:start_time];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSString* temp = [dateFormatter stringFromDate:date];
self.eventDate = [dateFormatter dateFromString:temp];
NSDateFormatter* timeFormatter = [[NSDateFormatter alloc]init];
[timeFormatter setDateFormat:#"HH:mm:ss"];
NSString* temp2 = [timeFormatter stringFromDate:date];
self.start_time = [timeFormatter dateFromString:temp2];
Now even though the conversion is successful the problem is that eventDate also has has time after date 00:00:00. How can i remove this so that eventDate only contains date.
Conversly start_time has the time of event but also has some arbritrary reference date before that. How can i remove that so i only have time in start_time
I have searched hard and fast but haven't been able to figure out this problem. Any help would be appreciated.
You cannot remove either the date or the time to keep only one component. If I remember correctly NSDate object is internally just a number of seconds relative to a fixed point in time. So every NSDate contains the full date and time information.
What you probably want to do is to get the NSDateComponents you want from a NSDate object.
Instead of trying to store this separate, just display these dates separate. I think it could be useful sometimes to get the date completly, but i don't know your idea.
You can try with it, it may be help you.
NSString *finalDate = #"2014-12-22T11:00:00+0500";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ssZZZ"];
NSDate *date = [dateFormatter dateFromString:finalDate];
//For getting Time
NSDateFormatter* df1 = [[NSDateFormatter alloc]init];
[df1 setDateFormat:#"hh:mm:ss"];
NSString *time = [df1 stringFromDate:date];
NSLog(#"time %# ", time);
//For getting Date
NSDateFormatter* df2 = [[NSDateFormatter alloc]init];
[df2 setDateFormat:#"yyyy-MM-dd"];
NSString *actualDate = [df2 stringFromDate:date];
NSLog(#"actualDate %# ", actualDate);

Getting a (null) result when attempting to format NSDate from MySQL datetime string

I have the following code:
- (NSString *)
lastSeenDateString:(NSString *)dateString
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone defaultTimeZone]];
[dateFormatter setDateFormat:#"yyyy-MM-ddTHH:mm:ssZ"];
NSDate *date = [dateFormatter dateFromString:dateString];
NSString *result = [NSDateFormatter localizedStringFromDate:date dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterShortStyle];
return result;
}
The dateString variable looks like this (I output to the log to make sure): 2014-05-20T17:23:42.000Z
The date variable, when output to log, shows: (null)
I've tried removing the setTimeZone method, changing setDateFormat to things many different things ("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd", etc.) and nothing works. No matter what I do, it returns null. I've looked at many other StackOverflow questions answering the same thing, as well as other samples on Google, and my code seems to line up with accepted answers. Yet, still nothing but a null NSDate variable results.
The input doesn't match the format.
[dateFormatter setDateFormat:#"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSSZ" ];
You need to put the T in single quotes, and you should include the milliseconds, SSS, in the format string.
Your date string appears to be a RFC 3339 date. As outlined in Technical Q&A 1480, to make sure you handle different international calendar settings, you want to parse that in the en_US_POSIX locale.
Thus:
- (NSString *)lastSeenDateString:(NSString *)dateString
{
NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:#"en_US_POSIX"];
// parse RFC 3339 date
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.locale = enUSPOSIXLocale;
dateFormatter.dateFormat = #"yyyy-MM-dd'T'HH:mm:ss.SSSZ";
NSDate *date = [dateFormatter dateFromString:dateString];
// switch back to current locale
dateFormatter.locale = [NSLocale currentLocale];
return [NSDateFormatter localizedStringFromDate:date dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterShortStyle];
}

Objective C - create NSDate from two Strings

Short version: Is there a way to combine two NSDates (which can be formed from two different strings) into a single NSDate object?
Detail: In my app, there are two textfields where the user enters the day and the time, respectively (these are entered using a customised Date Picker). When I want to save the information in the database, the property of the object expects a single date, comprised of both the day and the time.
Here is how I set the strings:
if ([mode isEqualToString:#"date"])
{
self.dateFormat = [[NSDateFormatter alloc] init];
[self.dateFormat setDateFormat:#"MM/dd/yy"];
self.dateTextField.text = [self.dateFormat stringFromDate:date];
}
else if ([mode isEqualToString:#"time"])
{
self.timeFormat = [[NSDateFormatter alloc] init];
[self.timeFormat setDateFormat:#"hh:mm a"];
self.timeTextField.text = [self.timeFormat stringFromDate:date];
}
where date is a NSDate passed in to the method. Now when I am trying to save the information in a different method, I have access to the strings and the date formats, so I am able to do
NSDate* tempDate = [self.dateFormat dateFromString: self.dateTextField.text];
NSDate* tempTime = [self.timeFormat dateFromString: self.timeTextField.text];
but that's as far as I can get... I'm not sure how to combine the dates together into a single entity. Would I combine the DateFormatter strings together somehow?
Thank you for your help :)
Try this.
NSString *strTemp = [NSString stringwithFormat:#"%# %#",self.dateTextField.text,self.timeTextField.text];
NSDateFormatter *dateFotmatter = [[[NSDateFormatter alloc] init] autorelease];
[self.dateFotmatter setDateFormat:#"MM/dd/yy hh:mm a"];
NSDate* tempDate = [self.dateFotmatter dateFromString:strTemp];
Hope it helps.
Enjoy coding.

Check NSString for specific date format

I have a NSString and I need to check that it is in a this specific format MM/DD/YY. I then need to convert that to a NSDate. Any help on this would be much appreciated. Sidenote - I have searched around and people suggest using RegEx, I have never used this and am unclear about it generally. Can anyone point me to a good resource/explanation.
NSString *strDate1 = #"02/09/13";
NSString *strDate2 = #"0123/234/234";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd/MM/yy"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"GMT"]];
NSDate *dateFormat1 = [dateFormatter dateFromString:strDate1];
NSDate *dateFormat2 = [dateFormatter dateFromString:strDate2];
NSLog(#"%#", dateFormat1); // prints 2013-09-02 00:00:00 +0000
NSLog(#"%#", dateFormat2); // prints (null)
So you will know when it's not formatted correctly if the NSDate is nil. Here's the link to the docs if you need more info: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW1
Use an NSDateFormatter for both tasks. If you can convert the string to a date then it is in the correct format (and you already have the result).
I know that this is a late answer, but it is impossible to always guarantee that a string is in this particular date format.
A date formatter, a regex, or even a human can not verify certain dates, because we don't know if the user is entering "mm/DD/yy" or "DD/mm/yy". It is common in some places to enter the day of the month first, while in other areas you enter the month first. So if they enter "09/06/2013" do they mean "September 6th" or the "9th of June"?
Here is a simple function for anyone searching for a simple solution.
- (BOOL) isTheStringDate: (NSString*) theString
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:theString];
if (dateFromString !=nil) {
return true;
}
else {
return false;
}
}
You have to change the formatter below to match the formatting your date is using.
[dateFormatter setDateFormat:#"yyyy-MM-dd"];

Resources