Trouble converting NSString to a NSDate - objective-c

I have looked at other examples and I am still not able to convert this string to a date. After i run this code I get the following output from the NSLogs:
Prediction Conversion: 2012-07-01 00:00:00 +0000
Timestamp Conversion: 2012-06-24 00:00:00 +0000
Prediction: 604800.000000
Which isn't the hard coded dates i used. Does anyone know why? Code is below:
NSString *timeStamp = #"20120620 19:23";//[[predictionData objectAtIndex:0 ] valueForKey:#"tmstmp"];
NSString *predictionTime = #"20120620 19:30";// [[predictionData objectAtIndex:0 ] valueForKey:#"prdtm"];
NSDateFormatter *ts = [[NSDateFormatter alloc] init];
[ts setDateFormat:#"yyyyMMdd HH:dd"];
NSDate *convertedTS = [ts dateFromString:timeStamp];
NSDateFormatter *pt = [[NSDateFormatter alloc] init];
[pt setDateFormat:#"yyyyMMdd HH:dd"];
NSDate *convertedPT = [pt dateFromString:predictionTime];
NSTimeInterval timeDifference = [convertedPT timeIntervalSinceDate:convertedTS];
NSLog(#"Prediction Conversion: %#", [convertedPT description]);
NSLog(#"Timestamp Conversion: %#", [convertedTS description]);
NSLog(#"Prediction: %f", timeDifference);
Thanks!

You are using dd for your minutes instead of mm. This:
[ts setDateFormat:#"yyyyMMdd HH:dd"];
Should be this:
[ts setDateFormat:#"yyyyMMdd HH:mm"];

You formatter string is incorrect.
HH:dd
should be
HH:mm
In addition, you need to take the timezone into consideration. Without +XXXX specified, UTC is used by default. To set the timezone:
[ts setTimeZone:[NSTimeZone /*timezone*/]];
where /*timezone*/ is specified by the NSTimeZone class. There are many different ways of using a timezone (and many different timezones), so choose the one that is best for you.

You need to set the locale, set it to en_us_POSIX.
ts.locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_us_POSIX"];
also, it should be HH:mm, not dd

Related

Not getting NSDate from string

I have following date in string formate "date string : 2014-09-28 17:30:00"
Now, I want to convert it into NSDate.
I have use following code for this.
NSString *date = #"2014-09-28 17:30:00";
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter1 dateFromString:date];
NSLog(#"date from string: %#", dateFromString);
I got the following output.
date from string: 2014-09-28 12:00:00 +0000
So, Here Time is changed.
Please tell me, How can I convert into NSDate. What I am missing here?
When you pass an NSDate object into NSLog, it will print the NSDate in GMT time, which may not be your timezone (and why you were getting 12:00 instead of 17:30), this would also cause the output of your NSLog statement to be different for people who are running your code in different timezones, so what you want to do is call the [NSDateFormatter stringFromDate:] method if you want to keep your specified time from your date object:
So replace this line of code:
// Will print out GMT time by default (+0000)
NSLog(#"date from string: %#", dateFromString);
With this line:
// Will honor the timezone of your original NSDate object:
NSLog(#"date from string: %#", [dateFormatter1 stringFromDate:dateFromString]);
And that should print out the value you were hoping for.
// --------------------------//
Note: It is important to understand that NSDate objects do not have any concept of timezones, so it is up to the developer to manage and track their timezones with the provided platform methods.
On iOS, you can look into using this class:
NSTimeZone, which can help you manage/assign your timezone(s) on iOS platforms.
If you are developing for OSX, you can assign a timezone and locale with this method: -descriptionWithCalendarFormat:timeZone:locale:. (Sadly, this method is OSX-only)
Hope that helps.
There is a time zone component attached to your log at the end that means the date is converted to the specified time zone..here greenwhich mean time
So converting into your time locale can give you the right value you inserted
In your first string add +0000 to the end and check again you can see the value is the same you get.ie the conversion is done on the GMT format
visit https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html
This documentation provides you how to convert NSString to date.
this code is provided by apple documentation.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:162000];
NSString *formattedDateString = [dateFormatter stringFromDate:date];
NSLog(#"formattedDateString: %#", formattedDateString);
// Output for locale en_US: "formattedDateString: Jan 2, 2001".
To make string as date
NSString *formattedDateString = [dateFormatter stringFromDate:date];
stringFromDate:
Returns a string representation of a given date formatted using the receiver’s current settings.
what you had used
dateFromString:
Returns a date representation of a given string interpreted using the receiver’s current settings.

Convert NSString in MM-dd-yy format to NSDate

In my application I am getting an NSString with the date as 01-22-12(MM-dd-yy). Now I want to convert that string into an NSDate. I used the code below. But it is giving the date as 2012-01-04 05:00:00 +0000
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MM-dd-yy"];
NSDate *dateFromString = [dateFormatter dateFromString:self.selectedWeek];
What is the proper way to convert my string to an NSDate?
From your original question I'm not totally clear whether you want:
1 the string as an NSDate.
or
2 to be able to get the original date NSString back out of an NSDate instance.
Your code is basically right. I just ran a slightly adapted version of it, which seemed to work fine:
NSString *dateString = #"01-22-12";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MM-dd-yy"];
NSDate *date = [dateFormatter dateFromString:dateString];
NSString *outString = [dateFormatter stringFromDate:date];
NSLog(#"%#",date);
NSLog(#"%#",outString);
This produced:
2013-02-24 09:57:24.352 datesAgain.m.out[787:707] 2012-01-22 00:00:00 +0000
2013-02-24 09:57:24.352 datesAgain.m.out[787:707] 01-22-12
So, either way the result seems to be what you were looking for. I suspect that the reason you are getting an incorrect value is that self.selectedWeek doesn't have the value you think it does. I'd inspect it, either in the debugger or with NSLog. If you are creating it somewhere else using another format string, be aware that they can be tricky and slightly unintuitive - for instance s means seconds, but S means fractions of a second.
Documentation available here - most recent Unicode formatting standard here (ios6.0/OSX 10.8) - also linked to in previous link, as are all previous relevant standards
you can use descriptionWithCalendarFormat:timeZone:locale:
NSString * mydate = [dateFromString descriptionWithCalendarFormat:#"%Y-%m-%d"
timezone:nil
locale:nil];

NSDate date don't give me the right hour

I'm trying to get the current date with :
NSLog(#"DATE NOW : %#", [NSDate date]);
But when I execute it, I have a difference of one hour between the date displayed and the current date.
Log http://data.imagup.com/12/1171458807.5637png
I found topics on questions like that but none of them gave me the answer.
How can I change that ?
You need to set the proper timezone. The default, as you can see, is UTC.
You can use a date formatter for doing that.
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone * timezone = [NSTimeZone timeZoneWithName:#"Europe/Rome"];
[dateFormatter setTimeZone:timezone];
[dateFormatter setTimeStyle:NSDateFormatterFullStyle
];
[dateFormatter setDateStyle:NSDateFormatterFullStyle];
NSLog(#"%#", [dateFormatter stringFromDate:[NSDate date]]);
For a list of available timezones you can use
NSArray *timeZoneNames = [NSTimeZone knownTimeZoneNames];
or check out the constants here on this Rails doc page.

Convert Short Zulu format date to NSDate

I am having troubles converting a short Zulu date format to a NSDate Object. I have found some answers for converting Zulu strings but mine looks like:
20111210T1000
And based on my researches, I am trying to do:
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:#"yyyyMMdd'T'HHmmss Z"];
NSDate *date = [f dateFromString:[str stringByReplacingOccurrencesOfString:#"Z" withString:#" +0000"]];
[f release];
I've tried many ways but my date is still nil...
How should I set my NSDateFormatter?
Here is a quick fix, in your date string you miss the timezone in the format, you should append (Paris one here) to your string and it should work. Also the format was wrong.
NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setDateFormat:#"yyyyMMdd'T'SSSZ"];
NSString* str = #"20111210T1000-0100"; // NOTE -0100, GMT +1 Paris zone
NSDate* date = [df dateFromString:str];
NSLog(#"%#", date);

current Date and Time - NSDate

I need to display the current Date and Time.
I have used ;
NSDate *currentDateNTime = [NSDate date];
I want to have the current date and time (Should display the system time and not GMT time).
The output should be in a NSDate format and not NSString.
for example;
NSDate *currentDateNTime = [NSDate date];
// Do the processing....
NSDate *nowDateAndTime = .....; // Output should be a NSDate and not a NSString
Since all NSDate is GMT referred, you probably want this:
(don'f forget that the nowDate won't be the actual current system date-time, but it's "shifted", so if you will generate NSString using NSDateFormatter, you will see a wrong date)
NSDate* currentDate = [NSDate date];
NSTimeZone* currentTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
NSTimeZone* nowTimeZone = [NSTimeZone systemTimeZone];
NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:currentDate];
NSInteger nowGMTOffset = [nowTimeZone secondsFromGMTForDate:currentDate];
NSTimeInterval interval = nowGMTOffset - currentGMTOffset;
NSDate* nowDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:currentDate];
Every moment in time is the same moment in time everywhere around the world —- it is just expressed as different clock times in different timezones. Therefore, you can't change the date to some other date that represents the time in your timezone; you must use an NSDateFormatter that you feed with the timezone you are in. The resulting string is the moment in time expressed in the clock time of your position.
Do all needed calculations in GMT, and just use a formatter for displaying.
Worth reading
Does [NSDate date] return the local date and time?
Some useful resources for anyone coming to this more recently:
Apple date and time programming guide do read it if you're doing anything serious with dates and times.
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/DatesAndTimes/DatesAndTimes.html#//apple_ref/doc/uid/10000039i?language=objc
Useful category on NSDate with lots of utilities does allow a ~new~ date to be generated based on an existing date.
https://github.com/erica/NSDate-Extensions
There's also a swift version of the category
https://github.com/erica/SwiftDates
You need an NSDateFormatter and call stringFromDate this method to get a string of your date.
NSDateFormatter *dateformater = [[NSDateFormatter alloc] init];
[dateformater setDateFormat:#"yyyyMMdd,HH:mm"];
NSString *str = [dateformater stringFromDate: currentDateNTime];
use this method
-(NSDate *)convertDateToDate:(NSDate *) date
{
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
NSDate *nowDate = [[[NSDate alloc] init] autorelease];
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
[formatter setDateFormat:#"yyyy-MM-d H:m:s"];
NSString * strdate = [formatter stringFromDate:date];
nowDate = [formatter dateFromString:strdate];
return nowDate;
}
this may return you what you want.
i hope you this may help you.