NSDateFormatter, show same date for all timezones - ios

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

Related

NSDateFormatterLongStyle string to NSDate

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

coversion of date and time from 31 May 2016 04:30 PM(current format) to 2016-05-31T16:30:00.000+05:30(Required format)

hi can any on help me in achiving this is the string which i have 31 May 2016 04:30 PM(NSSTring) 2016-05-31T16:30:00.000+05:30(Required Format)
NSString *dateString = dateandtime;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
used the following code but returns nil
The current format string does not contain any time zone information, so you have to set the time zone in the date formatter as well as the locale to be able to parse the string independently from the current locale.
The input format is dd MMM yyyy hh:mm a
NSString *dateString = #"31 May 2016 04:30 PM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:#"en_US_POSIX"];
dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:19800];
dateFormatter.dateFormat = #"dd MMM yyyy hh:mm a";
NSDate *dateFromString = [dateFormatter dateFromString:dateString];
dateFormatter.dateFormat = #"yyyy-MM-dd'T'HH:mm:ss.SSSZ";
NSString *stringFromDate = [dateFormatter stringFromDate:dateFromString];
Some how I tried and worked
NSString *myString = dateandtime;
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"dd MMM yyyy hh:mm a";
NSDate *yourDate = [dateFormatter dateFromString:myString];
dateFormatter.dateFormat = #"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ";
NSLog(#"%#",[dateFormatter stringFromDate:yourDate]);
Whatever you do, test that your code works if the user doesn't use an Indian timezone, and if the user uses 24 hour time instead of AM/PM on their phone. I assume your "dateandtime" was created by converting an NSDate to an NSString; it would be much better to not do that but start with the original NSDate.
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
NSString *currentDateString = #"2016-05-31T16:30:00.000+05:30";
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ"];
NSDate *currentDate = [dateFormatter dateFromString:currentDateString];
NSLog(#"CurrentDate:%#", currentDate);
you can use this code.

How can I convert and display this NSDate more efficiently?

Here is my code:
NSDateFormatter *df = [NSDateFormatter alloc]init];
df.dateFormat = #"yyyy-MM-dd HH:mm:ss";
NSDate *date = [df dateFromString:self.todayRecord.datetime];
self.todayRecord.datetime is a string that looks something like:
2016-02-15 12:33:00
I want to display the same date but without the seconds like this:
2016-02-15 12:33
The way I can think of right now is make another date formatter and just format out the seconds. Something like this:
df.dateFormat = #"yyyy-MM-dd HH:mm";
NSDate *date = [df dateFromString:self.todayRecord.datetime];
I did this and display became (null).
do like
//create the NSDateFormatter first
NSDateFormatter *df = [NSDateFormatter alloc]init];
// set the date format based on your String
df.dateFormat = #"yyyy-MM-dd HH:mm:ss";
// convert the string to date
NSDate *date = [df dateFromString:self.todayRecord.datetime];
// set the final dateformat what the output do you need
df.dateFormat = #"yyyy-MM-dd HH:mm";
// in here you get final output on String
NSString *finalString = [df StringFromdate:date];
// in here you get final output on date
NSDate *FinalDate = [df dateFromString:finalString];

iOS - Init NSDate with a stringDate without timezone calculations

I am getting a date time from web service which is in UTC format. Now i want to assign it to NSDate. Following is the code i have done
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss"];
NSDate *utcDate = [dateFormatter dateFromString:#"2015-08-18T23:00:00"];
but it is calculating its timezone calculations by default the result is 2015-08-19 03:00:00 +0000. How can i initialize NSDate with same date and Time. I want to perform timezone calculations later on
edit/update:
Xcode 11 • Swift 5.1:
let dateString = "2015-08-18T23:00:00"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
if let dateFromString = formatter.date(from: dateString) {
print(dateFromString) // "2015-08-18 23:00:00 +0000"
}
A default-allocated NSDateFormatter will use the current locale (the one that the user set up in Settings.app).
You have to explicitly set a suitable locale on the formatter:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
This locale uses the gregorian calendar on UTC without any DST adjustments.
Edit: LeoDabus points out that setting the locale does not change the timezone of the date formatter. This has to be done explicitly:
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
NSString *dateStr =[NSString stringWithFormat:#"%#",[dict valueForKey:#"utc_datetime"]];
NSString* input = dateStr;
NSString* format = #"dd MMM yyyy - HH:mm:ss'";
// Set up an NSDateFormatter for UTC time zone
NSDateFormatter* formatterUtc = [[NSDateFormatter alloc] init];
[formatterUtc setDateFormat:format];
[formatterUtc setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
// Cast the input string to NSDate
NSDate* utcDate = [formatterUtc dateFromString:input];
// Set up an NSDateFormatter for the device's local time zone
NSDateFormatter* formatterLocal = [[NSDateFormatter alloc] init];
[formatterLocal setDateFormat:format];
[formatterLocal setTimeZone:[NSTimeZone localTimeZone]];
// Create local NSDate with time zone difference
NSDate* localDate = [formatterUtc dateFromString:[formatterLocal stringFromDate:utcDate]];
NSLog(#"utc: %#", utcDate);
NSLog(#"local: %#", localDate);
NSDateFormatter *format1q = [[NSDateFormatter alloc] init];
format1q.dateFormat = #"HH:mm";
NSString *StrDAte=[NSString stringWithFormat:#"%#",[format1q stringFromDate:utcDate]];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"HH:mm";
NSDate *date = [dateFormatter dateFromString:StrDAte];
date = [date dateByAddingTimeInterval:-60];
dateFormatter.dateFormat = #"hh:mm a";
NSString *pmamDateString = [dateFormatter stringFromDate:date];

How to convert 24 hr String time into 12 hr time String format

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.

Resources