-2

This seems to be a very popular question, but I haven't found an answer that is applicable to my situation.

Consider my line of code:

 classHour.StartPoint = [NSDate dateWithTimeIntervalSince1970:[[thisEvent valueForKey:@"Start"] doubleValue]]; 

classHour.StartPoint is an NSDate.

thisEvent valueForKey:@"Start" is an NSString of value @"2016-01-13T07:30:00.0000000Z"

But somehow, classHour.StartPoint gets a value of '1970-01-01 00:33:36 UTC'

My question is twofold: Why is this happening, and -when corrected- do I indeed end up with a valid NSDate?

Sjakelien
  • 2,255
  • 3
  • 25
  • 43

1 Answers1

2

The reason this is not work is because you are trying to grab a double value from a string. I your case the string is 2016-01-13T07:30:00.0000000Z, which is not a double value, thus the value return is 2016.

2016 is return because - is not a valid double, this is where parsing will stop. But date create by dateWithTimeIntervalSince1970: is correct, because it is 2016 seconds since 1-1-1970 00:00:00.

You will need to use NSDateFormater to get the correct date value from the string.

NSDateFormatter *dateFormatter= [NSDateFormatter new];
dateFormatter.dateFormat = @"yyyy'-'mm'-'dd'T'HH:mm:ss.AZ";

NSString *dateString =[thisEvent valueForKey:@"Start"];
NSDate *date = [dateFormatter dateFromString:test];
rckoenes
  • 69,092
  • 8
  • 134
  • 166
  • Thank you so much! It has been a while since I have worked with NSDates. – Sjakelien Jan 15 '16 at 11:08
  • @rckoenes: this question is clearly a duplicate, could you explain, why you reopened it? – vikingosegundo Jan 15 '16 at 11:12
  • I ended up with "formatter.dateFormat = @"yyyy'-'mm'-'dd'T'HH:mm:ss.0000000Z";" to make it work in my situation. – Sjakelien Jan 15 '16 at 11:15
  • @vikingosegundo it's not really a duplicate, first of the question is why does this happen, which was not explained in your duplicate. There was just stated you should parse dates with `NSDateFormatter`. – rckoenes Jan 15 '16 at 11:36
  • The thread I chose as a duplicate answers sufficiently how to convert a string to a nsdate, or Correctly turn an NSString into NSDate. A clear duplicate. That here the OP proves by posting strange code that they did not invest any effort in researching does not change this. Otherwise no question with any — even unrelated — code could be closed as duplicate. – vikingosegundo Jan 15 '16 at 12:31
  • Well the question was why it was happing, just closing everything as a duplicate will not teach the OP what was going on. Not all question are just 'how do I?', sometimes people what to why something is not working. But you are entitled to your own opinion as am I. You may close it again if you feel that is correct. – rckoenes Jan 15 '16 at 12:58