convert hard code nsstring to nsdate - objective-c

say i have this nsstring * date = #"13th May-2015"
i want to convert it to something like this #"13/05/2015"
currently i am trying to do it with nsdateformatter:
NSString * dateStr = #"13th May-2015";
NSDateFormatter *dateFormatOriginal = [[NSDateFormatter alloc] init];
[dateFormatOriginal setDateFormat:#"dd MM-yyyy"];
NSDate *date = [dateFormatOriginal dateFromString:dateStr];
NSDateFormatter *dateFormatConverted = [[NSDateFormatter alloc] init];
[dateFormatConverted setDateFormat:#"dd/MM/yyyy"];
NSString * convertedDateString = [dateFormatConverted stringFromDate:date];
NSLog(#"this should be 13/05/2015, %#", convertedDateString);
so i expect the converted date string became to 13/05/2015.
but above code fail to do so....any help with code example would be helpful, thanks guys.

NSString * dateStr = #"13th May-2015";
NSArray *stringComponentArray = [dateStr componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSMutableArray *workingArray = [NSMutableArray arrayWithArray:stringComponentArray];
NSMutableString *dateString = [[NSMutableString alloc]initWithString:[workingArray firstObject]];
[dateString replaceOccurrencesOfString:#"st" withString:#"" options:NSCaseInsensitiveSearch range:NSMakeRange(0,[dateString length])];
[dateString replaceOccurrencesOfString:#"nd" withString:#"" options:NSCaseInsensitiveSearch range:NSMakeRange(0,[dateString length])];
[dateString replaceOccurrencesOfString:#"rd" withString:#"" options:NSCaseInsensitiveSearch range:NSMakeRange(0,[dateString length])];
[dateString replaceOccurrencesOfString:#"th" withString:#"" options:NSCaseInsensitiveSearch range:NSMakeRange(0,[dateString length])];
[workingArray replaceObjectAtIndex:0 withObject:dateString];
dateStr = [workingArray componentsJoinedByString:#" "];
NSDateFormatter *dateFormatOriginal = [[NSDateFormatter alloc] init];
[dateFormatOriginal setDateFormat:#"dd MM-yyyy"];
NSDate *date = [dateFormatOriginal dateFromString:dateStr];
NSDateFormatter *dateFormatConverted = [[NSDateFormatter alloc] init];
[dateFormatConverted setDateFormat:#"dd/MM/yyyy"];
NSString * convertedDateString = [dateFormatConverted stringFromDate:date];
NSLog(#"this should be 13/05/2015, %#", convertedDateString);
Since your date string doesn't match with any of the iOS Date formatter styles. Uou need to play with the strings.Please have a look into above solution.

13th May-2014 is not "dd MM-yyyy" format.
You have to make sure your input string matches the format string exactly.

Related

How to convert Date from JSON to NSDate

Hi I need to convert this string
"2013-12-05T08:58:55.9345456+02:00"
to NSDate
I am trying next format but without luck
"yyyy-MM-dd'T'HH:mm:SSSSSSSZZZZZ"
Code below.
Can you help me with right format
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
// "2013-12-05T08:58:55.9345456+02:00"
[dateFormat setDateFormat:#"yyyy-MM-dd'T'HH:mm:SSSSSSSZZZZZ"];
NSDate *date = [dateFormat dateFromString:jsonDateString];
Your format is close. You need:
yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZZZZZ
And be sure to set the formatter's locale to en_US_POSIX. This should always be done when parsing fixed formatted, non-localized strings.
NSString * dateStr = #"2013-12-05T08:58:55.9345456+02:00";
NSArray *dateStrParts = [dateStr componentsSeparatedByString:#"T"];
NSString *datePart = [dateStrParts objectAtIndex:0];
NSString *timePart = [dateStrParts objectAtIndex:1];
NSString *t = [[timePart componentsSeparatedByString:#"."] objectAtIndex:0];
NSString *newDateStr = [NSString stringWithFormat:#"%# %#",datePart,t];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
[df setDateFormat:#"yyyy-MM-dd HH:mm:ss"]; // Change here for your formated output
NSDate *date = [df dateFromString:newDateStr];
NSLog(#"%#",date);
Output
2013-12-05 08:58:55 +0000
The problem lies in the timezone where you have +02:00.
The ZZZZ only parses to +0000, hence you are getting nil.
You can do in this way:
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSString *jsonDateString = #"2013-12-05T08:58:55.9345456+02:00";//#"2013-12-05T08:58:55.9345456+02:00"
NSRange lastColon = [jsonDateString rangeOfString:#":" options:NSBackwardsSearch];
if(lastColon.location != NSNotFound) {
jsonDateString = [jsonDateString stringByReplacingCharactersInRange:lastColon withString: #""];
}
[dateFormat setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'.'SZ"];
NSDate *date = [dateFormat dateFromString:jsonDateString];
NSLog(#"%#",date)
EDIT:
As per rmaddy's comment, you should use SSSSS instead of single S.

Converting Date Format

How to convert this type of Date Format to yyyy-MM-dd HH:MM:ss format.
"DATE_OF_JOINING":"\/Date(1349634600000+0530)\/"
 I'd prefer a scanner over regular expressions to extract the time interval from the string
NSDictionary *dict = #{#"DATE_OF_JOINING" : #"Date(1357683534626+0530)"};
NSString *string = dict[#"DATE_OF_JOINING"];
NSString *intervalString;
NSString *offsetString;
NSScanner *scanner = [NSScanner scannerWithString:string];
[scanner setScanLocation:[string rangeOfString:#"("].location+1];
[scanner scanUpToCharactersFromSet:[NSCharacterSet characterSetWithCharactersInString:#"+-"] intoString:&intervalString];
[scanner scanUpToString:#")" intoString:&offsetString];
NSInteger hours = [[offsetString substringToIndex:3] integerValue];
NSInteger minutes = [[offsetString substringFromIndex:3] integerValue];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
offsetComponents.hour = hours;
offsetComponents.minute = minutes;
NSTimeInterval interval= [intervalString doubleValue];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval/1000];
date = [[NSCalendar currentCalendar] dateByAddingComponents:offsetComponents toDate:date options:0];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSString *result = [formatter stringFromDate:date];
use NSDateFormatter. This will let you format it many different ways, and into strings.
Here's apple's reference on the class for iOS:
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html

Sorting NSMutablearray by NSString as a date

I have an array, which is filled out with string objects. Inside each object is the name of the object and the string, seperated by " - ", ex. "Object1 - 26.05.2012 ". I would like to sort my array by the date in the string, and not the name, descending Is this possible?
As #Vladimir pointed out, it would be much better to separate the name and the string from each other and sort by the date.
NSMutableArray *newArray = [[NSMutableArray alloc] init];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd.MM.yyyy"];
for (NSString *str in yourArray)
{
NSRange rangeForDash = [str rangeOfString:#"-"];
NSString *objectStr = [str substringToIndex:rangeForDash.location];
NSString *dateStr = [str substringFromIndex:rangeForDash.location+1];
NSDate *date = [formatter dateFromString:dateStr];
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:objectStr, #"object", date, #"date", nil];
[newArray addObject:dic];
}
NSSortDescriptor *sortDesc = [[NSSortDescriptor alloc] initWithKey:#"date" ascending:NO];
[newArray sortUsingDescriptors:[NSArray arrayWithObjects:sortDesc, nil]];
[sortDesc release];
[formatter release];
newArray will be sorted but will have dictionary objects, each containing 2 strings.
Quick and dirty fix - rearrange the string so that the date is first
str = [[str substringFromIndex:someIndex] stringByAppendingString:[str substringToIndex:someIndex]];
then just switch everything back once the array is sorted.

How to make a string from a NSDate variable as well as another NSString variable

I am playing around with making a unique ID for whenever a button is pushed in my application. I basically want it to be two NSString variables that I make concatenated together.
So far, what I have got it mostly working as it gives me no errors in the code itself, but it does only give me (null) as my text in my label.
Where I have the 2 is basically a placeholder for where I will eventually have a variable that will look up what is in the plist for the username.
My code for this is:
NSString *UserID;
NSDate *TimeNow;
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyyMMddhhmm"];
UserID = [NSString stringWithFormat:#"",'Username'];
NSString *CurrentTime = [dateFormatter stringFromDate:TimeNow];
SessionID = [NSString stringWithFormat:#"%# %#", UserID, CurrentTime];
UniqueSessionID.text = SessionID;
You haven't initialised TimeNow. And your UserID is just being set to the empty string. To clean up that code, I would do this:
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyyMMddhhmm"];
NSString *CurrentTime = [dateFormatter stringFromDate:[NSDate date]];
NSString *SessionID = [NSString stringWithFormat:#"Username %#", CurrentTime];
UniqueSessionID.text = SessionID;
Update:
To have "Username" dynamic just do this:
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyyMMddhhmm"];
NSString *CurrentTime = [dateFormatter stringFromDate:[NSDate date]];
NSString *UserID = #"Some user";
NSString *SessionID = [NSString stringWithFormat:#"%# %#", UserID, CurrentTime];
UniqueSessionID.text = SessionID;
Then just change UserID to what you want the username to be.
I think that there should be:
NSDate *TimeNow = [NSDate date];
NSDate *dateFromString = [[NSDate alloc] init];
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy/MM/dd hh:mm"];//this is the date format of dateFromString
NSString *CurrentTime = [dateFormatter stringFromDate:TimeNow];
[dateFromString release];
UserID = [NSString stringWithFormat:#"",'Username'];
SessionID = [NSString stringWithFormat:#"%# %#", UserID, CurrentTime];
UniqueSessionID.text = SessionID;

Sort NSDictionaries in NSMutableArray by NSDate

I have a NSMutableArray with dictionaries, all of the dict's contain a NSDate is form of NSString with key 'Date'. I want to sort the NSDictionaries by the Dates. So for example i have the following state of the array:
Dict
Date
20.06.1996 23:30
Dict
Date
04.10.2011 19:00
Dict
Date
20.06.1956 23:39
And I want to sort it, so that it looks like this:
Dict
Date
20.06.1956 23:39
Dict
Date
20.06.1996 23:30
Dict
Date
04.10.2011 19:00
I have already experimented with NSSortDescriptor, but without success...
Update:
I have managed to sort the dates, but I came to this problem: In the dicts there is not only dates, also other objects, and what my code does is it only switches the date values between the dicts, instead of switching the complete dicts around. With this, the other values in the dicts get assigned a wrong date, which is very bad. Can anybody help me? Heres my code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"savedData.daf"];
NSMutableArray *d = [NSMutableArray arrayWithContentsOfFile:path];
for (int ii = 0; ii < [d count]; ii++) {
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
if (is24h) {
[dateFormatter setDateFormat:#"dd.MM.yyyy HH:mm"];
}
else {
[dateFormatter setDateFormat:#"dd.MM.yyyy hh:mm a"];
}
[dateFormatter setLocale:[NSLocale currentLocale]];
NSDate *dat = [dateFormatter dateFromString:[[d valueForKey:#"Date"] objectAtIndex:ii]];
NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
NSDictionary *oldDict = (NSDictionary *)[d objectAtIndex:ii];
[newDict addEntriesFromDictionary:oldDict];
[newDict setObject:dat forKey:#"Date"];
[d replaceObjectAtIndex:ii withObject:newDict];
[newDict release];
}
NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:#"Date" ascending:YES];
NSArray *sorters = [[NSArray alloc] initWithObjects:sorter, nil];
[sorter release];
NSMutableArray *sorted = [NSMutableArray arrayWithArray:[d sortedArrayUsingDescriptors:sorters]];
[sorters release];
NSLog(#"%#",sorted);
for (int ii = 0; ii < [sorted count]; ii++) {
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
if (is24h) {
[dateFormatter setDateFormat:#"dd.MM.yyyy HH:mm"];
}
else {
[dateFormatter setDateFormat:#"dd.MM.yyyy hh:mm a"];
}
[dateFormatter setLocale:[NSLocale currentLocale]];
NSString *sr = [dateFormatter stringFromDate:[[sorted valueForKey:#"Date"] objectAtIndex:ii]];
NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
NSDictionary *oldDict = (NSDictionary *)[d objectAtIndex:ii];
[newDict addEntriesFromDictionary:oldDict];
[newDict setObject:sr forKey:#"Date"];
[sorted replaceObjectAtIndex:ii withObject:newDict];
[newDict release];
}
NSLog(#"before: %#"
""
"after: %#",d,sorted);
[sorted writeToFile:path atomically:YES];
There are many ways to do this, one would be to use NSDate objects instead of NSStrings (or NSStrings formatted according to ISO 8601, so that the lexicographic sort would match the desired sorting). Then you could do:
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:#"Date"
ascending:YES];
[array sortUsingDescriptors:[NSArray arrayWithObject:descriptor]];
Or, if you can't (or don't want to) change your data, you can always sort using a block:
[array sortUsingComparator:^(id dict1, id dict2) {
NSDate *date1 = // create NSDate from dict1's Date;
NSDate *date2 = // create NSDate from dict2's Date;
return [date1 compare:date2];
}];
Of course this would probably be slower than the first approach since you'll usually end up creating more than n NSDate objects.
There are a couple of options, one is to put NSDate objects in the dictionary.
One problem with comparing the strings is that you can 't just do a string compare because the year is not in the most significant potion of the string.
So, you will need to write a comparison method to use with:
- (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr
or perhaps:
- (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context
The comparator will need to handle the dd.mm.yyyy hh:mm string format.
Other options include adding another dictionary key with an NSDate representation and sorting on that.