0

Is it possible to convert input string with any format into date?

I want to receive ate and time from textfield with any format like date: may 22 2000, wed may 20, may, 30 2000 etc.. and also need to get correct value according to the local timezone.

please help?

Jan49
  • 59
  • 1
  • 2
  • 8

1 Answers1

0

NSDateFormatter can help convert any type of date NSString to NSDate. The important thing is to use the right format for the date.

Here is some code you can try

NSString *dateString = @"01-02-2010";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"dd-MM-yyyy"];

NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];

You will have to set the date format to whatever format your string is in. Here are some date format specifiers: (Complete list here)

  • eeee - Local day of week spelled out
  • yyyy - year (4 digits)
  • MMMM - Month spelled out
  • dd - day of month with no leading zeros
  • HH - hour of day (24 hour format)
  • mm - minutes of hour (with leading zero)

Edit

The date format for the following dates will be:

  • May 03 2000 : "MMM dd yyyy"
  • Mon, Jan 03 : "eee, MMM dd"
  • Mon 31 Jan : "eee dd MMM"
aksh1t
  • 5,410
  • 1
  • 37
  • 55
  • But if i need to accept strings-- May 3 2000 & Mon, Jan 3 and Mon 31 Jan, so it is not working when i tried with [dateFormatter setDateFormat:@"dd-MM-yyyy"]; – Jan49 May 28 '14 at 10:38
  • Actually i need to accept strings in any format and convert to date. Is it possible? It is difficult to write diffrent time formats for every string i entered in the textfield – Jan49 May 28 '14 at 10:39
  • You have to set the `setDateFormat` according to your string. so for you it will be "MMMM dd yyyy" – aksh1t May 28 '14 at 10:39
  • If you don't know what format the date is coming in the string, I don't think it can be converted without giving the format to `NSDateFormatter`. – aksh1t May 28 '14 at 10:43
  • I want to accept these 3 types of strings(mentioned above) and and convert in to date so i have to write 3 different formats? – Jan49 May 28 '14 at 10:44
  • Yes you will have to write the three formats, each for the appropriate date. – aksh1t May 28 '14 at 10:45
  • SO there is no other way? are you sure? – Jan49 May 28 '14 at 10:49
  • If you mean to convert a string to NSDate in such a way that you do not have to enter the format, then NO, there is no way. – aksh1t May 28 '14 at 10:51
  • I think you need to process the NSString and make it into a specific format , then convert it using NSDateFormatter – EL Kamel May 28 '14 at 10:55
  • Actually my need is , to accept date from variety timezones and store and update. So in these case i have to write all timezone fromate? – Jan49 May 28 '14 at 10:55