Converting can NSString to NSDate format in object

2019-09-25 07:41发布

问题:

This question already has an answer here:

  • Convert string to date in my iPhone app 4 answers
  • issue with date formatting using NSDateFormatter 3 answers

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];

回答1:

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).


回答2:

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.



回答3:

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);