iOS Dateformatter Timezone - ios

Im trying to convert a String without timezone value like "31.05.2015" to NSDate.
Whats wrong with my DateFormatter? It returns the date 2015-05-31 22:00:00 +0000
and when I try to print it with the same formatter it prints: 01.06.2015
-(NSDateFormatter*) dateFormatter{
if(!_dateFormatter){
_dateFormatter = [[NSDateFormatter alloc]init];
[_dateAndTimeFormatter setDateFormat:#"dd.MM.yyyy"];
[_dateAndTimeFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"CEST"]];
_dateFormatter.dateStyle = NSDateFormatterShortStyle;
_dateFormatter.timeStyle = NSDateFormatterNoStyle;
}
return _dateFormatter;
}
EDIT
I updated it to
-(NSDateFormatter*) dateAndTimeFormatter{
if(!_dateAndTimeFormatter){
_dateAndTimeFormatter = [[NSDateFormatter alloc]init];
[_dateAndTimeFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss.SSS Z"];
_dateAndTimeFormatter.dateStyle = NSDateFormatterShortStyle;
_dateAndTimeFormatter.timeStyle = NSDateFormatterShortStyle;
}
return _dateAndTimeFormatter;
}
and call it with
NSDate *startDate = [self.dateFormatter dateFromString:#"31.05.2015"];
self.beginningValueLabel.text = [self.dateFormatter stringFromDate:startDate];
The result still is 01.06.2015.
startDate is 2015-05-31 22:00:00 +0000

When you use [NSDateFormatter setTimeZone:] the formatter will adjust the date for display based on that new timezone, so it's adding the timezone offset to the date before formatting it for display.
The NSDateFormatter defaults to the timezone of the device, so it would have had the same effect as setting the timezone manually. Tell the DateFormatter to use the same timezone as the date (+0000).
dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]

Related

NSDate from String returning nil

I am storing dates as strings in the format: 2018-07-10 21:00:29 +0000
I created a formatter to convert the strings back into dates:
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
formatter.dateFormat = #"yyyy-MM-dd'T'HH:mm:ss.SSSZ";
[formatter setLocale:[NSLocale currentLocale]];
NSDate *date = [formatter dateFromString:[chore getDate]];
However, the date that is returned is always nil. Does anyone know what I'm doing wrong?
You set the wrong format in the dateformat. So it will always return the nil value.
The following method can return the date in the NSDate format.
-(NSDate *)convertDate :(NSString *)date1 //the argument date1 is the string date you used
{
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
formatter.dateFormat = #"yyyy-MM-dd HH:mm:ss Z"; // the format which you used in the string date
[formatter setLocale:[NSLocale currentLocale]]; //This for set the Locale .It is not compulsory.
NSDate *date = [formatter dateFromString:date1];
return date;
}
Refer to date formatter date formats here:
You need to update your date format to something like:
"yyyy-MM-dd HH:mm:ss Z"

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

Convert NSDate to NSString with a small bug

I used this snippet to convert a given date to a string. But if the date happens to have a time of less than 5:00 then the result is a prior date. For example, this date: "07-01-15 05:00:00 +0000" will work correctly. But a "07-01-15 04:49:00 +0000" will have a prior date as the result.
Any suggestions?
+(NSString *)stringFromGivenDate:(NSDate *)date
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"MM-dd-yy";
NSString *dateString = [dateFormatter stringFromDate:date];
NSLog(#"date: %#", dateString);
return dateString;
}
NSDateFormatter by default sets the time zone to your locale time zone.
But while converting date to string changes the time to GMT time.
So you have to set the time zone using
dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"]
or whatever timezone you want(like #"GMT+5:30").
So your code will be like:
+(NSString *)stringFromGivenDate:(NSDate *)date
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"MM-dd-yy";
dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"]
NSString *dateString = [dateFormatter stringFromDate:date];
NSLog(#"date: %#", dateString);
return dateString;
}

NSDateFormatter not Working for Twitter date

I am trying to format a date i am getting from twitter using the STTwitter library.
However the code that I've tried so far has not worked.
Code for getting the date from twitter:
NSString *dateString = [status valueForKey:#"created_at"];
This returns the time, date, time zone and year in which the tweet was made which looks messy.
I tried using the following code to convert this and make it neater:
NSDateFormatter *dateFormatter =[[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"MMddHHmm"];
NSDate *dateFromString = [dateFormatter dateFromString:dateString];
NSLog(#"%#", dateFromString);
dateFormatter =[[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"dd MMMM' at 'hhmm a"];
NSString *mydate=[dateFormatter stringFromDate:dateFromString];
And then try to put the result in a text label:
cell.detailTextLabel.text = my date;
Ive tried many different variations of the Date Formatter but none have worked and i have no idea why.
Thanks for your help :)
The date format you are using is not even close the date string used in the result, which is something like Fri Nov 18 20:35:49 +0000 2011.
NSString *dateStr = #"Fri Nov 18 20:35:49 +0000 2011";
NSDateFormatter *dateFormatter= [NSDateFormatter new];
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
[dateFormatter setDateFormat:#"EEE MMM dd HH:mm:ss Z yyyy"];
NSDate *date = [dateFormatter dateFromString:dateStr];
The real trick is in the locale used, since the date is localized in english.
STTwitter has a category for that:
NSString *s = [tweet valueForKey:#"created_at"];
NSDate *date = [[NSDateFormatter stTwitterDateFormatter] dateFromString:s];
I created a gist with Swift implementation of it:
https://gist.github.com/appzzman/62339fcd10bbe8fce256 It takes Twitter date and lets you specify the output format of the date.
import UIKit
func parseTwitterDate(twitterDate:String, outputDateFormat:String)->String?{
let formatter = NSDateFormatter()
formatter.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
var indate = formatter.dateFromString(twitterDate)
var outputFormatter = NSDateFormatter()
outputFormatter.dateFormat = "hh:mm a dd:MM:yy"
var outputDate:String?
if let d = indate {
outputDate = outputFormatter.stringFromDate(d)
}
return outputDate;
}
var str = "Wed Sep 02 19:38:03 +0000 2009"
var outputDateFormat = "hh:mm a dd:MM:yy"
parseTwitterDate(str, outputDateFormat)

Weird converting output from NSString to NSDate

I have weird result trying to output NSDate object from NSString.
My NSString is: 1976-06-11
My method to convert is:
-(NSDate*)dateFromString:(NSString *)dateString{
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd"];
NSDate *date = [dateFormat dateFromString:dateString];
return date;
}
But it output 1976-06-10 21:00:00 +0000
How could that happen? Difference in 1 day.
You have date in UTC format. Use this code to converting your date to local time:
NSTimeInterval seconds; // assume this exists
NSDate *ts_utc = [NSDate dateWithTimeIntervalSince1970:seconds];
NSDateFormatter *utcFormatter = [[NSDateFormatter alloc] init];
utcFormatter.timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
utcFormatter.dateFormat = #"yyyy.MM.dd G 'at' HH:mm:ss zzz";
NSDateFormatter *localFormatter = [[NSDateFormatter alloc] init];
localFormatter.timeZone = [NSTimeZone timeZoneWithName:#"EST"];
localFormatter.dateFormat = #"yyyy.MM.dd G 'at' HH:mm:ss zzz";
NSString *utcDateString = [utcFormatter stringFromDate:ts_utc];
NSString *LocalDateString = [localFormatter stringFromDate:ts_utc];
Or you can use [NSTimeZone defaultTimeZone] to prevent hardcoded strings for timezone names. This method returns the system time zone, If no default time zone has been set.
You can use following methods to convert an UTC date string into UTC date and local date
- (NSDate *)convertIntoGMTZoneDate:(NSString *)dateString
{
NSDateFormatter *gmtFormatter = [[NSDateFormatter alloc]init];
[gmtFormatter setDateStyle:NSDateFormatterFullStyle];
[gmtFormatter setTimeStyle:NSDateFormatterFullStyle];
[gmtFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"GMT"]];
return [gmtFormatter dateFromString:dateString];
}
- (NSDate *)convertIntoSystemZoneDate:(NSString *)dateString
{
NSDateFormatter *systemZoneFormatter = [[NSDateFormatter alloc]init];
[systemZoneFormatter setDateStyle:NSDateFormatterFullStyle];
[systemZoneFormatter setTimeStyle:NSDateFormatterFullStyle];
[systemZoneFormatter setTimeZone:[NSTimeZone systemTimeZone]];
return [systemZoneFormatter dateFromString:dateString];
}
func dateFromString(dateString: String) -> NSDate {
// Convert string to date object
var dateFormat = NSDateFormatter()
dateFormat.dateFormat = "yyyy-MM-dd"
dateFormat.timeZone = NSTimeZone(name: "UTC")
var date = dateFormat.dateFromString(dateString)!
print(date)
return date
}
output :
1976-06-11 00:00:00 +0000
If you debug code, it shows 1 day difference but after run you will find the actual date which is you enter.
It works for me.I think it will helps you.
Thank you

Resources