Converting can NSString to NSDate format in objective C [duplicate]

泪湿孤枕 提交于 2019-12-13 09:46:19

问题


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


来源:https://stackoverflow.com/questions/19539502/converting-can-nsstring-to-nsdate-format-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!