Objective C - create NSDate from two Strings - ios

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.

Related

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);

Why is my formatter returning a nil NSDate

The following code will set date to nil.
NSString *dateString = #"2014-04-27T04:20:07.000-04:00";
NSString *UTC_FORMAT = #"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:UTC_FORMAT];
NSDate *date = [formatter dateFromString:dateString];
What am I doing wrong?
I've tried many other different variations for UTC_FORMAT, but counldn't seem to get it. I'm also a little bit confused as to when and where the single quotes go. After playing with this for a while, I'm assuming it can goes around characters that shouldn't be interpreted by the formatter, but that's a separate thing.
Related Links That Couldn't Help Me:
Apple Docs: Data Formatting Guid
SO: Why is NSDateFormatter returning nil?
Formats That I've Tried:
NSString *UTC_FORMAT = #"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'";
NSString *UTC_FORMAT = #"yyyy-MM-dd'T'HH:mm:ss-Z";
Your date looks like a quite standard JSON date format in RFC3339 format. However, there are several possibilities how these dates can be formatted. In this case, your date string contains milliseconds. Your date format doesn't, so this cannot work. The following code will check for dates without fractional seconds first, then for dates with fractional seconds. Furthermore, you are looking for a literal character Z instead of a timezone.
The "X5" is documented at
http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns
and converts time zones in quite a flexible way, including the colon in the middle. .SSSSSS will convert fractional parts of seconds up to microseconds. Should you be given nanoseconds change it to nine S characters.
And I forgot the locale information...
NSString *UTC_FORMAT = #"yyyy'-'MM'-'dd'T'HH':'mm':'ssX5";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:UTC_FORMAT];
enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
gmtTimeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
[formatter setLocale:enUSPOSIXLocale];
[formatter setTimeZone:gmtTimeZone];
NSDate *date = [formatter dateFromString:dateString];
if (date == nil)
{
NSString *UTC_FORMAT2 = #"yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSSSSSX5";
NSDateFormatter *formatter2 = [[NSDateFormatter alloc] init];
[formatter2 setDateFormat:UTC_FORMAT2];
[formatter2 setLocale:enUSPOSIXLocale];
[formatter2 setTimeZone:gmtTimeZone];
date = [formatter2 dateFromString:dateString];
}
To avoid dependencies on the current locale, add :
NSString *dateString = #"2014-04-27T04:20:07.000-04:00";
NSString *UTC_FORMAT = #"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:UTC_FORMAT];
[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"]];
NSDate *date = [formatter dateFromString:dateString];

loosing 1 hour after formatting a date string

i am formatting a date string with the following code:
and this is the format of the date string : 2013-10-08T20:30:00+03:00
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
[dateFormatter setDateFormat:#"EEEE"];
NSDateFormatter *formmatter = [[NSDateFormatter alloc] init];
formmatter.dateFormat = #"yyyy-MM-dd'T'HH:mm:SSSZZZ";
NSString *dataString = [meetingData objectForKey:#"start"];
if (![dataString isKindOfClass:[NSNull class]]) {
NSMutableString *mutableDate = [dataString mutableCopy];
[mutableDate deleteCharactersInRange:NSMakeRange(mutableDate.length - 3, 1)];
NSDate *gmtDate = [formmatter dateFromString:mutableDate];
NSDateFormatter *HHMM_Fromatter = [[NSDateFormatter alloc] init];
[HHMM_Fromatter setDateFormat:#"HH:mm"];
self.meetingTime = checkTheObject([HHMM_Fromatter stringFromDate:gmtDate]);
self.meetingDay = checkTheObject([dateFormatter stringFromDate:gmtDate]);
}
the output is forself.meetingTime : 19:30
and self.meetingDay is fine, why am i loosing 1 hour?
Your two date formatters HHMM_Fromatter and dateFormatter use different locales and thus, different time zones. You should explicitly set the timezone of both formatters to the same zone (probably [NSTimeZone localTimeZone]).
Note that the remaining parts of your date code seems fragile. You shouldn't do string calculations to remove the time zone from a string representation.
NSDate represents an absolute point in time and is not affected by time zones or locales. You should parse the string to one single NSDate and then use this date to calculate user facing string representations that take time zones into account.

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"];

Make NSDate Equal to NSString

I have a string:
stringValue = 2013-06-11 06:01:28.
When i try to convert it using NSDateFormatter it becomes like this: date = 2013-06-10 22:01:28 +0000.
I've read that they are the same point in time. In fact when i get the string value of the date, i get the string above.
If they're the same, is there a way to have a date with value equal to my string above? Can i have an NSDate *date = 2013-06-11 06:01:28? If yes, how can I do that?
It happen because when you convert string to date it convert to GMT time format
if you want date same as your string value than you have to set your stadard local time
Like
NSDate *date=[[NSDate alloc]init];
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setTimeZone:[NSTimeZone timeZoneWithName:#"Asia/Kolkata"]];
[timeFormat setDateFormat:#"yyyy-MM-dd HH:mm:ss'"];
date = [timeFormat dateFromString:#"2013-06-11 06:01:28"];
hope it may help you
Use this formatter:
NSDateFormatter* f = [[[NSDateFormatter alloc] init] autorelease];
[f setDateFormat:#"yyyy-MM-dd hh:mm:ss"];

Resources