-3

How can i convert the following string "October 24,Monday 12:30 AM EST" to NSDateFormat.

i tried this code

NSDateFormatter *dateformat=[[NSDateFormatter alloc]init];
[dateformat setDateFormat:@"MM/DD/YYYY hh:mm a"];
NSDate *datefor=[dateformat dateFromString:appDelegate.appoinmentString];
[dateformat setDateFormat:@"MM-dd-yyyy hh:mm a"];
NSString *dateStr=[dateformat stringFromDate:datefor];

NSDate *datetype=[dateformat dateFromString:dateStr];
Randyka Yudhistira
  • 3,612
  • 1
  • 26
  • 41
Vasu
  • 41
  • 1
  • 8
  • The dateFormat you put ti your DateFormatter does't match the one from the String – Larme Oct 23 '13 at 10:45
  • You asked 7 Questions till now and you didn't Accept any of them. If you find any Answer helpful to you then you should mark it as "Accepted". So, it will increase your "Accept-Rate" as well as helpful for future visitors also. – Bhavin Oct 23 '13 at 11:05

3 Answers3

8

Your dateformat for October 24,Monday 12:30 AM EST is not correct. The correct dateformat in your case is MMMM dd,eeee HH:mm a z.


Working Code :

NSDateFormatter *dateformat = [[NSDateFormatter alloc] init];
[dateformat setDateFormat:@"MMMM dd,eeee HH:mm a z"];
NSDate *myDate = [dateformat dateFromString:@"October 24,Monday 12:30 AM EST"];

Take a look at Date Format Specifiers.

  1. eeee - Local day of week spelled out.
  2. MMMM - Month spelled out.
  3. dd - day of month with no leading zeros.
  4. HH - hour of day (24 hour format).
  5. mm - minutes of hour (with leading zero) .
  6. z - timezone (short wall time).
Bhavin
  • 27,155
  • 11
  • 55
  • 94
1

Try this...

NSString *p=@"October 24,Monday 12:30 AM EST";
NSDateFormatter *dateformat=[[NSDateFormatter alloc]init];
[dateformat setDateFormat:@"MMM dd,EEEE hh:mm a vvv"];
NSDate *datefor=[dateformat dateFromString:p];
[dateformat setDateFormat:@"MM-dd-yyyy hh:mm a"];
NSString *dateStr=[dateformat stringFromDate:datefor];

NSDate *datetype=[dateformat dateFromString:dateStr];

Let me know if you have any problem.

user1673099
  • 3,293
  • 7
  • 26
  • 57
0

Try like below:-

NSString *dateStr=@"October 24,Monday 12:30 AM EST";
[dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"EST"]];
[dateFormat setDateFormat:@"MMMM dd,eeee HH:mm a z"];

NSDate *changeDate=[dateFormat dateFromString:dateStr];
NSLog(@"changeDate=%@",changeDate);
NSString *str=[dateFormat stringFromDate:changeDate];

//getting your local time
NSTimeZone *tz=[NSTimeZone localTimeZone];
//setting yourlocal time
[dateFormat setTimeZone:tz];
NSDate *date = [dateFormat dateFromString:str];
//Setting your desired format
[dateFormat setDateFormat:@"dd-mm Z"];
NSString *newDate=[dateFormat stringFromDate:date];
NSLog(@"new date=%@",newDate);
Hussain Shabbir
  • 14,801
  • 5
  • 40
  • 56