0

I've a NSDateFormatter set like this:

YYYY/MM/dd HH:mm:ss

I can convert it from NSDate to NSString and from NSString to NSDate. But what I want is to get the NSDate as I formatted it. I thought about converting it to NSString then convert back to NSDate but this way is just awful, I'm sure there is a simpler way, right?

Idan Moshe
  • 1,675
  • 4
  • 28
  • 65
  • 1
    That's like saying I want an integer `123` to exist as `1-2-3`. An integer is an integer. You can't change its inherent data type representation. Same with dates. – Aaron Mar 18 '14 at 17:13
  • If you want to get it as you formatted it, just leave it formatted. If you want to parse/display it accurately, use "yyyy" instead of "YYYY". – Hot Licks Mar 18 '14 at 17:14

3 Answers3

7

You can't format an NSDate, it is an exact point in time. If you are converting an NSDate to a string, and back to a NSDate, they will be identical

Logan
  • 52,262
  • 20
  • 99
  • 128
  • So, there is no way to get NSDate like my syntax 'YYYY/MM/dd HH:mm:ss'? – Idan Moshe Mar 18 '14 at 17:04
  • 2
    @IdanMoshe An NSDate object has no intrinsic string representation. It simply internally represents the number of milliseconds since some reference date. In order to convert that number to a nice-looking format, you need to use an NSDateFormatter. – Alexis King Mar 18 '14 at 17:06
  • No, there is no way. But there is a way to get such a representation of a date. See the link I posted. – Amin Negm-Awad Mar 18 '14 at 17:06
  • 3
    An NSDate isn't stored that way, it represents a fixed point in time. The format isn't formatting the date, it's providing information for the dateformatter on how to decode whatever you sent it and convert it to an nsdate. – Logan Mar 18 '14 at 17:06
  • 4
    If I would get a penny for each Q of this type, … I would have an expensive yacht, an expensive house and cheap girls. – Amin Negm-Awad Mar 18 '14 at 17:08
2

A date is never formatted. The string representation and only the string representation of a date is formatted.

Unexpected value from NSDate

Community
  • 1
  • 1
Amin Negm-Awad
  • 16,582
  • 3
  • 35
  • 50
1

May be you want to write simple category to NSDate that will return right formatted string?

NSDate+formatted.h

@interface NSDate (formatted)

-(NSString)formatedString;

@end

NSDate+formatted.m

@implementation  NSDate (formatted)
-(NSString)formatedString
{
// your formatter code here 
}
@end 
sage444
  • 5,661
  • 4
  • 33
  • 60