How to save only time zone without GMT? - ios

I am using this code for getting time zone
NSMutableArray *arrResult = [NSMutableArray new];
NSDateFormatter *dateFormatter = [NSDateFormatter new];
NSDate *myDate = [NSDate date];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
[dateFormatter setTimeStyle:NSDateFormatterLongStyle];
[dateFormatter setDateFormat:#"ZZZ"];
[[NSTimeZone knownTimeZoneNames] enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:obj];
[dateFormatter setTimeZone:timeZone];
NSString *dateString = [dateFormatter stringFromDate: myDate];
NSMutableString *mu = [NSMutableString stringWithString:dateString];
[mu insertString:#":" atIndex:3];
NSString *strResult = [NSString stringWithFormat:#"(GMT%#)%#",mu,obj];
[arrResult addObject:strResult];
}];
NSLog(#"%#", arrResult);
the response of this code is like this as what i want
"(GMT+01:00)Africa/Libreville",
"(GMT+00:00)Africa/Lome",
"(GMT+01:00)Africa/Luanda",
"(GMT+02:00)Africa/Lubumbashi",
"(GMT+02:00)Africa/Lusaka",
"(GMT+01:00)Africa/Malabo",
"(GMT+02:00)Africa/Maputo",
"(GMT+02:00)Africa/Maseru",
"(GMT+02:00)Africa/Mbabane",
"(GMT+03:00)Africa/Mogadishu",
"(GMT+00:00)Africa/Monrovia",
"(GMT+03:00)Africa/Nairobi",
"(GMT+01:00)Africa/Ndjamena",
"(GMT+01:00)Africa/Niamey",
"(GMT+00:00)Africa/Nouakchott",
"(GMT+00:00)Africa/Ouagadougou",
"(GMT+01:00)Africa/Porto-Novo",
"(GMT+00:00)Africa/Sao_Tome",
"(GMT+02:00)Africa/Tripoli",
"(GMT+01:00)Africa/Tunis",
i have to show this type in my label
but what i have to do is when we click on save only (Africa/Tripoli) this part in the database will be saved , i am not getting how to do this .
please help me

If you don't want (GMT+01:00) this bracket in list then you can make string like,
NSString *strResult = [NSString stringWithFormat:#"%#",obj];
[arrResult addObject:strResult];
So, that bracket part will not come.
If you want that bracket part and name both together also for different task then you can make another array called arrResult2 and make another string called strResult2 and do as i mentioned above.
So, you have two arrays. one(arrResult) have both that bracket and names and one(arrResult2) have names only.
If you want to separate string then,
NSString *str = #"(GMT+00:00)Africa/Lome";
NSString *newStr = [str substringFromIndex:11];
NSLog(#"new str : %#",newStr);
I found that every string have closing bracket at 11th index, so you can use it to get sub string from original one.
Hope this will help :)

I got the answer after many try if anyone want this then see here:-
NSString *zoneString = #"(GMT+13:00)Pacific/Tongatapu"
NSUInteger location = [zoneString rangeOfString:#")"].location+1;
NSLog(#"Trimed string:%#",[zoneString substringFromIndex:location]);
Trimed string:Pacific/Tongatapu

Related

Convert Datetime c# to Objective c and invertion

How to convert Datetime timestamp to a NSDate?
How to make the inverse?
My method to convert datetime to a string :
+(NSString*) dateTojson:(NSDate*)date{
return [NSString stringWithFormat:#"/Date(%f)/",(double)([date dateWithTimeIntervalSince1970] * 1000)];
}
My inverse method:
+(NSDate*) jsonToDate:(NSString *)json
{
double milisec = 0;
json = [[[json stringByReplacingOccurrencesOfString:#"/Date(" withString:#""] stringByReplacingOccurrencesOfString:#"/" withString:#""] stringByReplacingOccurrencesOfString:#"-0200" withString:#""];
NSArray *arr = [json componentsSeparatedByString:#"-"];
for(NSString *s in arr) {
if(![s isEqualToString:#""]){
milisec += [s doubleValue];
}
}
NSDate *date = [NSDate dateWithTimeIntervalSince1970:(milisec / 1000.0)];
return date;
}
When i use [self jsonToDate:#"/Date(1495497600)/"] where 1495497600 represents "05/23/2017", the method return me a wrong date (result = "01/18/1970").
Why?
Notes:
i'm not considering the time, only date.
My variable milisec is equals to 1495497600, so i think the problem is the method dateWithTimeIntervalSince1970.
already try some posts like:
Convert milliseconds to NSDate
How to Convert a milliseconds to nsdate in objective C
You don't really need to divide the milliseconds at the end:
NSDate *date = [NSDate dateWithTimeIntervalSince1970:milisec];
Result:
2017-05-23 00:00:00 +0000

NSString remove a non braking space

Let's say I get a string "123 4,56" from the following code (I have a Russian local at the moment which has comma as a default separator rather than a dot), how do I remove the space from it which in reality is a non breaking space and the standard code like [str stringByReplacingOccurrencesOfString:#" " withString:#""]; will not work:
NSString* amount = #"1234.56";
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_UK"]];
NSNumber *num = [formatter numberFromString:amount];
NSString* str = [NSString localizedStringWithFormat:#"%.2F", [num doubleValue]];
NSLog(#"Str Value: %#", str);
NSString *newStr = [str stringByReplacingOccurrencesOfString:#" " withString:#""];
NSLog(#"New Str Value: %#", newStr);
The output I get is:
Str Value: 1 234,56
New Str Value: 1 234,56
The problem I'm trying to solve is I get a string from the server which is a currency (i.e. 123.45) and I need to display that in the UITextField. The problem is that I can't just display the value as it comes from the server because it is dependant on the user local. If the user has a UK local that works fine, however if the user has a Russian local I need to display a comma instead of a dot, thus basically what the code above does. The issue I however get is that after converting the string from one local to another there is an annoying space added to it that I'm trying to get rid of.
Solution based on Doro answer
[str stringByReplacingOccurrencesOfString:#"\u00a0" withString:#""];
It sounds strange, did you check that that was exactly whitespace character?
i can offer this snippet for striping input characters using scanner:
- (NSString*) stripInputValue: (NSString*) inputValue
{
NSMutableString *strippedString = [NSMutableString
stringWithCapacity:inputValue.length];
NSScanner *scanner = [NSScanner scannerWithString:inputValue];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setLocale:[NSLocale currentLocale]];
NSString *decimalSymbol = [formatter decimalSeparator];
NSCharacterSet *validCharacters = [NSCharacterSet characterSetWithCharactersInString:[#"1234567890" stringByAppendingString:decimalSymbol]];
while ([scanner isAtEnd] == NO) {
NSString *buffer;
if ([scanner scanCharactersFromSet:validCharacters intoString:&buffer]) {
[strippedString appendString:buffer];
} else {
[scanner setScanLocation:([scanner scanLocation] + 1)];
}
}
return strippedString;
}
Be careful - if you want to support multiply locales - some locales uses '.' as separator, some ','. You can check this programmatically, if needed.
EDIT
Also please note that iOS doesn't use a space as a separator but a non-breaking space (U+00A0) for localizedStringWithFormat: so that is your problem.
Hope this helps.
The first line should have worked
NSString* newStr = [str stringByReplacingOccurrencesOfString:#" " withString:#""];
But just in case it didn't, I have another way for you:
NSString* newStr2 = [[str componentsSeparatedByString:#" "] componentsJoinedByString:#""];
UPDATE:
Instead of playing with the locale manually, you should use dynamic locale method for your requirement.
Replace: [formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_UK"]];
By:
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[formatter setLocale:[NSLocale currentLocale]];

How to get the data from a row in an NSArray using only part of the row to search

Lets say i have an array filled with several rows
dates = [NSArray arrayWithObjects:#"2012-05-01||Blue", #"2012-05-02||Red", #"2012-05-03||Green", #"2012-05-04||Orange", #"2012-05-05||Yellow", #"2012-05-06||Purple", #"2012-05-07||Silver", nil];
and then I have a date to search by 2012-05-01
How do i search for an object by only part of it without doing a big for( loop because this array will theoretically hold a few thousand cells.
EDIT:
if necessary how do i load the data into an NSDictionary? (i've never used them)
I know i can get the data like so
for(NSString *row in dates) {
NSString *date = [[row componentsSeperatedByString:#"||"] objectAtIndex:0];
NSString *color = [[row componentsSeperatedByString:#"||"] objectAtIndex:1];
}
NSMutableDictionary *colorsAndDates = [[NSMutableDictionary alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
for(NSString *row in dates) {
NSString *dateString = [[row componentsSeparatedByString:#"||"] objectAtIndex:0];
NSDate *date = [dateFormatter dateFromString:dateString];
NSString *color = [[row componentsSeparatedByString:#"||"] objectAtIndex:1];
[colorsAndDates setObject:color forKey:date];
}
If I am correct, this will format it into an NSDictionary, and then I can grab the color using:
NSString *dateToFind = #"2012-05-01";
NSDate *date = [dateFormatter dateFromString:dateToFind];
NSString *theColor = [colorsAndDates objectForKey:date];
Knowing this, I will have to go back and make it all revolve around NSDictionary instead of the strings they're in.
There's a couple of things you can do other than looping through the array:
1) Use a sorted array. Even if you need to keep the data in the initial order, you can make a sorted copy of it. Then you can do a binary search (if there are n items, check the n/2 item, if it's less than your date and repeat the process with only the data from n/2 to n, or if it's greater, then repeat with the data from 0 to n/2. Sort once, find many.
2) Create a dictionary on the fly using the data. You can use the the 10 character prefix of the data as the key. You'll have to maintain the dictionary along with the array, so this may not be practicable if you have a lot of changes. Create dictionary once, find many. (Note: despite the answers you've gotten, a dictionary may not be the best solution, particularly if you don't have unique keys (i.e. more than one record with the same date).
3) Forget the arrays and store your data in sqlite, and write a sql statement to get it. Most useful if you have a whole lot of data. You can use sqlite to build a primary key if you have duplicate dates in your data.
Creating a dictionary:
NSDictionary *dateDictionary = #{
#"2012-05-01" : #"Blue",
#"2012-05-02" : #"Red",
#"2012-05-03" : #"Green",
#"2012-05-04" : #"Orange",
#"2012-05-05" : #"Yellow",
#"2012-05-06" : #"Purple",
#"2012-05-07" : #"Silver"
};
NSString *date = #"2012-05-01";
NSString *dateColor = dateDictionary[date];
Using the example you gave (looping through the array to create a dictionary):
NSMutableDictionary *dateDictionary = [NSMutableDictionary dictionary];
for(NSString *row in dates) {
NSString *date = [[row componentsSeperatedByString:#"||"] objectAtIndex:0];
NSString *color = [[row componentsSeperatedByString:#"||"] objectAtIndex:1];
dateDictionary[date] = color;
}
NSString *date = #"2012-05-01";
NSString *dateColor = dateDictionary[date];

How to generate random string in Objective C based on core data values

I am developing one iPad application using storyboard and core data.For my application i need to generate one random string like 'M000142140502343524' which are not already exist in the 'data' field of the 'tableA' when click a button.
Common way to generate an unique string is
NSString *UUID = [[NSUUID UUID] UUIDString];
or
NSString *identifier = [[NSProcessInfo processInfo] globallyUniqueString];
But you also could create such string yourself. For example:
+ (NSString *)createRandomName
{
NSTimeInterval timeStamp = [ [ NSDate date ] timeIntervalSince1970 ];
NSString *randomName = [ NSString stringWithFormat:#"M%f", timeStamp];
randomName = [ randomName stringByReplacingOccurrencesOfString:#"." withString:#"" ];
return randomName;
}
You can generate a unique identifier (UUID) like this:
NSString *randomUUIDString = [[NSUUID UUID] UUIDString];
This will generate the random key
NSTimeInterval today = [[NSDate date] timeIntervalSince1970];
NSString *intervalString = [NSString stringWithFormat:#"%f", today];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:[intervalString doubleValue]];
NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
[formatter setDateFormat:#"yyyyMMddhhmm"];
NSString *strdate=[formatter stringFromDate:date];

Parsing NSString

I am currently at the point to where I want to create a simple text file, read it into my application, convert the string "0700 1300" to an NSDate format to be read into my native calendar.
I am pretty new to objective-c but I am trying to read in both 0700 into the start time of an event and 1300 into the end time of an event. I just cant get the 1300. Mainly I want to store the first WORD "0700" and the second WORD "1300".
EDIT:
If possible please include code that converts the string "0700 1400" to a string will later be the time interval of
EKEvent *myEvent;
This is the code I use to store the data within the text file I'm downloading from the web.
NSData *data = [[NSData alloc] initWithData:downloadFile.receivedData];
NSString *dataString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
[self.myDataArray addObject:dataString];
myDataArray is a mutable array which I initiated earlier in viewDidLoad of my current view controller.
This is a small snippet of the textfile im reading in.
Sunday
0 1200
Sunday
2100 2400
Monday
0 600
I was able to parse my text file but now the issue of converting the string that contains the start date and end date to an NSDATE.
I am not looping through the entire file yet, just one line within the specific file, i'll loop through the entire file once I can format ONE line at least.
I currently have converted 0 and 1200 to 2013-06-08 00:00:00 +0000 and 2013-06-08 12:00:00 +0000 by appending and inserting.
Heres the code I used.
NSData *data = [[NSData alloc] initWithData:downloadFile.receivedData];
NSString *dataString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSArray *components = [dataString componentsSeparatedByString:#"\n"];
NSString *anotherString = [NSString stringWithFormat:components[1]];
NSArray *times = [anotherString componentsSeparatedByString:#" "];
NSMutableString *startDate = [[NSMutableString alloc] initWithString:times[0]];
NSMutableString *endDate = [[NSMutableString alloc] initWithString:times[1]];
for (int i = startDate.length; i < 4; i++)
[startDate appendString:#"0"];
[startDate appendString:#":00 +0000"];
for (int i = endDate.length; i < 4; i++)
[endDate appendString:#"0"];
[endDate appendString:#":00 +0000"];
[startDate insertString:#":" atIndex:2];
[endDate insertString:#":" atIndex:2];
[startDate insertString:#"2013-06-08 " atIndex:0];
[endDate insertString:#"2013-06-08 " atIndex:0];
I realized that when adding events, I don't need to know the end time just the time interval. So i plan on taking the start TIME and comparing it to the end TIME and find the time interval that way.
I understand the DATE i give my string is of a constant date but that isn't the issue at the moment, I'll fix that later. But for now I would like to convert the NSString *startDate I created and stored the date/time string in to an NSDate *startDate so that I can use it as the start dat of an EKEvent.
Thank you guys.

Resources