-4

I wish to change the date format from "2013-01-21 11:55:00" to "Jan 21, 2013 5:30 AM".

I tried the below code. But it gives a constant date.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];

NSDate *myDate = [NSDate dateWithTimeIntervalSinceReferenceDate:162000];
NSLog(@"%@",[dateFormatter stringFromDate:myDate]);

The above code gives constant output : Jan 3, 2001 2:30:00 AM

But in my case, date is dynamic.

Ambili B Menon
  • 1,249
  • 2
  • 14
  • 26
  • If you want the output to be dynamic; Your inputs cannot be static. You are passing `162000`, and that's why you are getting constant output (with time changed, I guess). – viral Apr 02 '13 at 07:11
  • http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns – Chandu Apr 02 '13 at 07:22

3 Answers3

2
    NSString *firstDate = @"2013-01-21 11:55:00";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy'-'MM'-'dd  HH':'mm':'ss"];
    NSDate *date = [dateFormatter dateFromString:firstDate];
    [dateFormatter setDateFormat:@"MMM d, yyyy h:mm a"];

    NSLog(@"Expected Result___ %@",[dateFormatter stringFromDate:date]);
βhargavḯ
  • 9,786
  • 1
  • 37
  • 59
1

Try this

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"MMM d, yyyy h:mm a"];

NSDate *myDate = [NSDate dateWithTimeIntervalSinceReferenceDate:162000];
NSLog(@"%@",[dateFormatter stringFromDate:myDate];

Try [NSDate date] instead [NSDate dateWithTimeIntervalSinceReferenceDate:162000].

Hasintha Janka
  • 1,608
  • 1
  • 14
  • 27
0

well you get constant output since you give constant input as 162000 !!!

First get the date from the string using its format then use the new format to get string from the obtained date

use this to output format as

@"MMM d, yyyy h:mm a"

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"MMM d, yyyy h:mm a"];
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);
Lithu T.V
  • 19,955
  • 12
  • 56
  • 101