3

I am fresher to ios. I want to change the textField entered date(mm/dd/yyyy) format to (yyyy/mm/dd) and store the resulted date in a string. Would you please help me in this problem.

For example if i will enter date in textField like 11/23/2013(mm/dd/yyyy). It has to change to 2013/11/23(yyyy/mm/dd) and store it in a string. Thanks in advance.

Mike Z
  • 4,121
  • 2
  • 31
  • 53
Ramesh Rayadurgam
  • 75
  • 1
  • 1
  • 10
  • 1
    Best practice, store the date as an `NSDate` which is the time since first instant of 1 January 2001, GMT. That way it is not dependent on timezone, summertime/wintertime or format. That way two people in different parts of the world who save the current time at the same time will save the same the same time, GMT. When you want to display it use NSDateFormatter as appropriate. – zaph Nov 13 '13 at 12:20
  • Strange! this question are getting up votes. Probably @Ramesh is doing wrong voting. Question should be close as it is very common. – TheTiger Nov 13 '13 at 12:23
  • +1 for best practice advice from @Zaph. – Aditya Nov 13 '13 at 12:37
  • @The Tiger probably because mamy people have this issue and see it when looking at new questions. They don't care if it is a common question or if there are other answers, they just resonate with the question. – zaph Nov 13 '13 at 12:52

2 Answers2

14

This should do what you want to do:

NSString *dateString = @"11-13-2013";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM-dd-yyyy"];
NSDate *date = [dateFormatter dateFromString:dateString];

// Convert date object into desired format
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSString *newDateString = [dateFormatter stringFromDate:date];
Mike Z
  • 4,121
  • 2
  • 31
  • 53
3

You can format your string using dd/MM/yyyy hh:mm:ss a

Sample code:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd/MM/yyyy hh:mm:ss a"];
NSLog(@"%@", [dateFormatter dateFromString:@"12/12/2012 12:12:12 AM"]);

Please note SS/ss MM/mm are different. where MM represents months mm is for minutes etc. For more details please check the Apple Docs

Amar
  • 13,202
  • 7
  • 53
  • 71
Aditya
  • 2,876
  • 4
  • 34
  • 30