Converting can NSString to NSDate format in object

2019-09-25 07:19发布

This question already has an answer here:

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

3条回答
干净又极端
2楼-- · 2019-09-25 07:35

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);
查看更多
三岁会撩人
3楼-- · 2019-09-25 07:58

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.

查看更多
迷人小祖宗
4楼-- · 2019-09-25 07:59

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).
查看更多
登录 后发表回答