I have a UIDataPicker in my viewController with default location, when my user finishes selecting the date I run this code:
NSString *dateString = [NSDateFormatter localizedStringFromDate:[self.dataPicker date]
dateStyle:NSDateFormatterLongStyle
timeStyle:NSDateFormatterNoStyle];
With that code I can storage the date in the following format:
May 31, 2016
Later in my code I need to convert this string into a real date format, for this I use the code below:
-(NSDate*)convertStringToDate:(NSString*)date{
NSString *dateString = date;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
[dateFormatter setDateFormat:#"MM/dd/yyyy"];
return [dateFormatter dateFromString:dateString];
}
But this code return a null value. As the datepicker is set by default, my system can receive any date format, but in the end I want it to be converted to the format en_us.
How I can solve this problem?
Don't store the date as a string; store it as an offset, in seconds, from some reference date.
i.e:
uint64_t offset = (uint64_t)[[self.dataPicker date] timeIntervalSinceReferenceDate];
// store this 64-bit unsigned integer.
This takes less space and is quicker to convert to/from an NSDate object.
You can leave the offset as an NSTimeInterval (64-bit floating point double) if you prefer, but as you aren't storing date & time, uint64_t should do...
Use this code,
-(NSDate*)convertStringToDate:(NSString*)date{
NSString *dateString = date;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
[dateFormatter setDateFormat:#"MMM d, yyyy"];
return [dateFormatter dateFromString:dateString];
}
hope its helpful
The formatting string depends on the locale you are using. From the localizedStringFromDate documentation:
Returns string representation of a given date formatted for the
current locale using the specified date and time styles.
This method uses a date formatter configured with the current default
settings. The returned string is the same as if you configured and
used a date formatter as shown in the following example:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.formatterBehavior = NSDateFormatterBehavior10_4;
formatter.dateStyle = dateStyle; formatter.timeStyle = timeStyle;
NSString *result = [formatter stringForObjectValue:date];
Means, you should do the next:
-(NSDate*)convertStringToDate:(NSString*)dateString {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.formatterBehavior = NSDateFormatterBehavior10_4;
dateFormatter.dateStyle = NSDateFormatterLongStyle;
dateFormatter.timeStyle = NSDateFormatterNoStyle;
return [dateFormatter dateFromString:dateString];
}
Related
In my application I receive dates as string from server, for example "2016-09-28T16:51:15.000+0700". I use NSDateFormatter to get NSDate:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd'T'HH:mm:ss.SSSZ";
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
And another formatter to get string from NSDate to display it in UI
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.timeStyle = NSDateFormatterShortStyle;
dateFormatter.dateStyle = NSDateFormatterShortStyle;
It works correctly and shows date and time depending on timezone, but now I have requirement that the application should display same date and time for all timezones and displaying date and time should be equal to date and time from server response. So for example if the application receives "2016-09-28T16:51:15.000+0700" then it should always display it as 9/28/2016, 4:51 PM. How can I do it? It is possible to achieve it without changing response format for date and time?
If you really really want to ignore the time zone information in the received string cut it out for example using regular expression
NSString *dateString = #"2016-09-28T16:51:15.000+0700";
NSString *truncatedDateString = [dateString stringByReplacingOccurrencesOfString:#"\\.\\d+(\\+|-)\\d+"
withString:#""
options:NSRegularExpressionSearch
range:NSMakeRange(0, dateString.length)];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd'T'HH:mm:ss";
NSDate* date = [dateFormatter dateFromString:truncatedDateString];
dateFormatter.dateFormat = #"M/d/yyyy h:mm a";
NSString *finalDateString = [dateFormatter stringFromDate: date];
NSLog(#"%#", finalDateString); // 9/28/2016 4:51 PM
I would like to format a date to display in a uitableview custom cell
The data is passed into the app from a CMS - it is provided as a string in the following format and stored in a date type variable-
2014-04-15 10:10:45 +0000
Our app will initially be UK based - so I need to convert the format into DD/MM/YYYY format.
I tried the following code to parse my date (dateadded which is of type date).
NSDateFormatter *formatter = [NSDateFormatter new];
cellRecP.artDate.text = [formatter stringFromDate:resItem.dateadded];
but this just returns null - i guess the date format provided above is not anything that stringfromdate understands - is there any other way to format date?
Use an 'NSDateFormatter'
NSDateFormatter* newFormatter = [[[NSDateFormatter alloc] init] autorelease];
with this format to parse the string
[newFormatter setDateFormat:#"yyyy-MM-dd hh:mm:ss zzz"];
NSDate* aDate = [newFormatter dateFromString:dateString];
and you should get a valid 'NSDate' object
Try This and also Checkout this All Formate It is really good and helpful.
NSString *yourString = #"2014-04-15 10:10:45 +0000";
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setTimeZone:[NSTimeZone systemTimeZone]];//Set Your Timezone
[df setDateFormat:#"yyyy-MM-dd HH:mm:ss Z"];//You have to set this formate.
NSDate *dd = [df dateFromString:yourString];//This will convert into date;
//Now you can set your formate.
[df setDateFormat:#"dd/MM/yyyy"];
NSString *str = [df stringFromDate:dd];
You need an NSDateFormatter and a proper unicode parse string. NSDateFormatter by default automatically checks the device locale setting the correct output.
This is an example from some code of mine:
NSDateFormatter *dateWriter = [[NSDateFormatter alloc] init];
dateWriter.dateFormat = #"yyyy'-'MM'-'dd' 'HH':'mm':'ss' 'ZZZ";
dateWriter.dateStyle = NSDateFormatterMediumStyle;
dateWriter.timeStyle = NSDateFormatterMediumStyle;
Pay attention that date formatters are pretty expensive to create.
I have time in NSString like "15:15"
I want to covert this NSString time into 12 hr NSString(i.e "3:15 PM").
Use NSDateFormatter to turn the string in a NSDate. Then use the dateformatter again to change the NSDate to a string.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"HH:mm";
NSDate *date = [dateFormatter dateFromString:#"15:15"];
dateFormatter.dateFormat = #"hh:mm a";
NSString *pmamDateString = [dateFormatter stringFromDate:date];
Code might contain some errors, written without compiling or testing.
#python
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
[dateFormatter setLocale:locale];
[dateFormatter setDateFormat:#"hh:mm"];
Hope this helps!
Check out this SO question: NSDateFormatter dateFromString and iPhone in 24 Hour Format Confusion
You should be able to use to use NSDateFormatter to format the style of time you want, then read in the string to the formatter and pull it back out in your desired format.
I need to convert date from this format: "2011-11-04T18:30:49Z"
To this format: "MM/dd/yy hh:mm:SS a"
With the addition of the users system currentGMTOffset offset extracted by:
NSTimeZone* currentTimeZone = [NSTimeZone localTimeZone];
NSInteger currentGMTOffset = [currentTimeZone secondsFromGMT];
Any help will be greatly appreciated.
Thanks!
This snippet is going to help you to convert your formated string to a NSDate.
// Current date.
NSString *currentDate = #"2011-11-04T18:30:49Z";
// NSDateFormatter stuff.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"]];
[dateFormatter setDateFormat:#"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
// Convert to NSDate.
NSDate *neededDate = [dateFormatter dateFromString:currentDate];
Then you just need to convert to your requested format.
Im using ARC so no memory management is required.
Take a look at NSDateFormatter. You'll need to setup a date format and timezone on the date formatter object, and then you can convert strings to dates and dates to strings.
+ (NSString *)userVisibleDateTimeStringForRFC3339DateTimeString:(NSString *)rfc3339DateTimeString {
/*
Returns a user-visible date time string that corresponds to the specified
RFC 3339 date time string. Note that this does not handle all possible
RFC 3339 date time strings, just one of the most common styles.
*/
NSDateFormatter *rfc3339DateFormatter = [[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
[rfc3339DateFormatter setLocale:enUSPOSIXLocale];
[rfc3339DateFormatter setDateFormat:#"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
[rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
// Convert the RFC 3339 date time string to an NSDate.
NSDate *date = [rfc3339DateFormatter dateFromString:rfc3339DateTimeString];
NSString *userVisibleDateTimeString;
if (date != nil) {
// Convert the date object to a user-visible date string.
NSDateFormatter *userVisibleDateFormatter = [[NSDateFormatter alloc] init];
assert(userVisibleDateFormatter != nil);
[userVisibleDateFormatter setDateStyle:NSDateFormatterShortStyle];
[userVisibleDateFormatter setTimeStyle:NSDateFormatterShortStyle];
userVisibleDateTimeString = [userVisibleDateFormatter stringFromDate:date];
}
return userVisibleDateTimeString;
}
This might help.
NSString *lower = [NSString stringWithFormat:#"%#",[newDates objectAtIndex:0]];
NSString *higher = [NSString stringWithFormat:#"%#",[newDates objectAtIndex:[newDates count]-1]];
NSLog(#"%#",lower);
NSLog(#"%#",higher);
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyy-MM-dd"];
NSDate *dtLower = [df dateFromString:lower];
NSDate *dtHigher = [df dateFromString:higher];
[df release];
NSDateFormatter *df1 = [[NSDateFormatter alloc] init];
[df1 setDateFormat:#"yyyy-MM-dd"];
NSString * lowerDate = [df1 stringFromDate:dtLower];
NSString * higherDate = [df1 stringFromDate:dtHigher];
UILabel *dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 31, self.view.frame.size.width, 30)];
[dateLabel setTextColor:[UIColor grayColor]];
dateLabel.text = [NSString stringWithFormat:#"%# - %#",lowerDate,higherDate];
[self.view addSubview:dateLabel];
Output of lower and higher in Console is:
2011-05-23 14:55:52.767 Vocab[4225:207] 2011-05-23 03:58:22
2011-05-23 14:55:53.781 Vocab[4225:207] 2011-05-23 07:14:56
Here the above code does not work for me. The value for higher and lower are not null but when I try converting it into NSDate using NSDateFormatter then it returns nil.
So dtLower and dtHigher return nil
What could be wrong?
Try setting [df setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
[df setDateFormat:#"yyyy-MM-dd hh:mm:ss"];
Your first date format is wrong.
If you're working with user-visible dates, you should avoid setting a date format string as it's very hard to predict how your format string will be expressed in all possible user configurations. Rather, you should try and limit yourself to setting date and time styles (via -[NSDateFormatter setDateStyle:] and -[NSDateFormatter setTimeStyle:]).
If you're working with fixed-format dates, you should first set the locale of the date formatter to something appropriate for your fixed format. In most cases the best locale to choose is en_US_POSIX, a locale that's specifically designed to yield US English results regardless of both user and system preferences. en_US_POSIX is also invariant in time and between machines (en_US_POSIX works the same on iOS as it does on OSX, and as it it does on other platforms).
Once you've set en_US_POSIX as the locale of the date formatter, you can then set the date format string and the date formatter will behave consistently for all users.
The above info and more can be found in Apple's Technical Q&A QA1480
Here's a snippet of code which implements the recommendation from the above Technical Note:
static NSDateFormatter* dateFormatter = nil;
if (!dateFormatter)
{
dateFormatter = [NSDateFormatter new];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc]
initWithLocaleIdentifier:#"en_US_POSIX"];
[dateFormatter setLocale:enUSPOSIXLocale];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
dateFormatter.dateFormat = #"EEE, dd MMM yyyy HH:mm:ss +0000";
}