-1

I am trying to solve an issue for quite a long time.... i used almost all formats in objective C but not getting proper result.

I have below string coming from SQL server along with other data:

Aug 31 2015 14:40:11

I want to convert it like below:

8/31/2015 2:40 PM

My questions are:

  • Do i have to change the way DateTime field being send from sql ?

  • How i can achieve in Objective C ?

NeverHopeless
  • 11,077
  • 4
  • 35
  • 56
user2813740
  • 517
  • 1
  • 7
  • 29

2 Answers2

1

Try this

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[dateFormatter setDateFormat:@"dd-MMM-YYYY hh:mm:ss"];
NSDate *date = [dateFormatter dateFromString:@"Aug 31 2015 14:40:11"];
[dateFormatter setDateFormat:@"MM/dd/yyyy HH:mm a"];
NSLog(@"Your converted date - %@",[dateFormatter stringFromDate:date]);
Rajat
  • 10,977
  • 3
  • 38
  • 55
  • i notice for above answer it shows null, if date is in AM then date show correct .... but for above it shows date as null...can u plz help me out in this – user2813740 Sep 02 '15 at 14:08
  • NSDate *date = [dateFormatter dateFromString:@"Aug 31 2015 14:40:11"]; – user2813740 Sep 02 '15 at 14:40
  • Here you have to pass your string in which you are getting the date, if you are getting the diffrent date format then you have to change @"dd-MMM-YYYY hh:mm:ss" to the format in which you are getting the date or else you will get nil. – Rajat Sep 02 '15 at 14:44
  • [dateFormatter setDateFormat:@"MM-dd-YYYY hh:mm:ss"]; NSDate *date = [dateFormatter dateFromString:@"Aug 31 2015 04:40:11"]; works fine. but [dateFormatter setDateFormat:@"MM-dd-YYYY hh:mm:ss"]; NSDate *date = [dateFormatter dateFromString:@"Aug 31 2015 14:40:11"]; shows null only difference is time..... – user2813740 Sep 02 '15 at 15:13
0

It is better if you get the date in the required format from SQL, since SQL server supports several date formats to represent a date. On the other hand, if you want to manage in iOS, you have NSDateFormatter and NSDateComponent classes.

Here is an example, see loretoparisi's solution.

Community
  • 1
  • 1
NeverHopeless
  • 11,077
  • 4
  • 35
  • 56