My method receives a Dictionary named responseDict which contains keys, such as id, status, name, phoneNumber, date etc. in
responseDict[#"data"][#"value"][n]
(n for number)
If our code uses NSUserDefaults to access data:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
How can I change the date MySQL attribute 2017-05-12 10:00:00 to Dec 5, 2017 10 AM?
I tried the following, but it does not seem to change the defaults in the UILabel.
[defaults setInteger:[dictionary[#"id"] integerValue] forKey:#"ID"];
[defaults setObject:dictionary[#"status"] forKey:kNSUDoctorStatus];
[defaults setInteger:[dictionary[#"dur"] integerValue] forKey:#"duration"];
[defaults setObject:[NSString stringWithFormat:#"%# some",dictionary[#"date"]] forKey:#"date"];
[defaults synchronize];
Edit:
UILabel
The UILabel seems to have been added to the view by:
UILabel *vb = (UILabel *)[self.view viewWithTag:personMessageViewTag];
which was defined by:
#define personMessageViewTag 3001
Doctor Class
There is also a PersonDetailView class initialized:
PersonDetailView *personOnTheView;
And called in a method:
personOnTheView = [PersonDetailView sharedInstance];
personOnTheView.delegate = self;
[personOnTheView updateValues];
[self.view addSubview:personOnTheView];
Method:
Here is the code for [personOnTheView updateValues]
-(void)updateValues{
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
NSString *strImageUrl = [NSString stringWithFormat:#"%#%#",baseUrlForXXHDPIImage,[ud objectForKey:kOnGoingBookingPersonProfileImageKey]];
_doctorName.text = [ud objectForKey:kOnGoingBookingPersonNameKey];
NSString *at = [NSString stringWithFormat:#"%#",flStrForObj([Helper getLocalDate:[ud objectForKey:kOnGoingBookingPersonBookingDate]])];
_appoinmentTime.text = at;
float rating = [[ud objectForKey:kOnGoingBookingPersonRatingKey] floatValue];
_starRatingView.value = rating;
[_profilepic sd_setImageWithURL:[NSURL URLWithString:[Helper removeWhiteSpaceFromURL:strImageUrl]]
placeholderImage:[UIImage imageNamed:#"doctor_image_thumbnail"]
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL){
}];
}
Problem:
Everytime I change or modify:
[defaults setObject:dictionary[kPNPayloadAppoinmentTimeKey] forKey:kOnGoingBookingPersonBookingDate];
To:
[defaults setObject:[NSString stringWithFormat:#"%# some",dictionary[#"date"]] forKey:#"date"];
or just as simple as:
[defaults setObject:#"Something here" forKey:#"date"];
It displays blank.
Additional Information Edit:
[Helper getLocalDate] code:
+(NSString *)getLocalDate:(NSString *)gmtdate {
NSString *dateStr = gmtdate;
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *destinationDate = [dateFormatter1 dateFromString:dateStr];
NSDateFormatter *dateFormatters = [[NSDateFormatter alloc] init];
[dateFormatters setDateFormat:#"MMM d, yyyy HH a"];
dateStr = [dateFormatters stringFromDate: destinationDate];
// NSLog(#"DateString : %#", dateStr);
return dateStr;
}
With the help of this method you can get the date in local format if you having time zone in date string
-(NSDate*)convertDateToLocal:(NSString *)strDate
{
NSDateFormatter *localFormat = [[NSDateFormatter alloc] init];
[localFormat setDateFormat:#"yyyy-MM-dd HH:mm:ss z"];
NSDate *localDate = [localFormat dateFromString:strDate];
return localDate;
}
Here are two public method for date conversion if you don't have time zone
1) Date from string,
+ (NSDate *)dateFromString:(NSString *)strSource inFormat:(NSString *)strTargetFormat
{
NSDateFormatter *dtfFormatter = [[NSDateFormatter alloc] init];
[dtfFormatter setDateFormat:strTargetFormat];
return [dtfFormatter dateFromString:strSource];
}
2) String from date,
+ (NSString *)stringFromDate:(NSDate *)dtSourceDate inFormat:(NSString *)strTargetFormat
{
NSDateFormatter *dtfFormatter = [[NSDateFormatter alloc] init];
[dtfFormatter setDateFormat:strTargetFormat];
if (dtSourceDate != nil)
return [dtfFormatter stringFromDate:dtSourceDate];
else
return #"";
}
Hope this helps.
Related
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;
I have a datepicker and I save the value to .plist file with key UserDate in string format.
The value returns from datepicker is in 2013-02-13 11:17:34 +0000 format.
In order to save it into to .plist file I need to convert datepicker to string 2013-02-14T19:17:34Z
In other View, I want to retrieve back the UserDate from plist and compare with the user current date. I want days and hours different.
I convert and pass 2012-02-12 19:17:34 +0800 as destinationDate to compare with [NSDate new].
I managed to calculate the difference between two date. But the result is not correct.
How to get the correct difference result for two dates between iPhone's date and Datepicker's date? Do I need to use a specific timezone?
Extra info: I live in GMT+8. I set the simulator datepicker to Feb 13 2012, yet the result still say the countdown has 18hours and 4 minutes.
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
int units = NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *components = [calendar components:units fromDate:[NSDate date] toDate:destinationDate options:0];
[datelabel setText:[NSString stringWithFormat:#"%d%c %d%c %d%c %d%c %d%c", [components month], 'm', [components day],
'd', [components hour], 'h', [components minute], 'm', [components second], 's']];
NSLog
Edit
Plist file.
save method
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPath = [paths objectAtIndex:0];
// get the path to our Data/plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"Data.plist"];
// set the variables to the values in the text fields
self.userTitle = myTitle.text;
self.userMessage = myMessage.text;
NSLog(#"METHOD SAVE");
NSLog(#"Datepicker value = %#", myDate.date );
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSString *mdate = [dateFormatter stringFromDate:myDate.date];
// [dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSLog(#"Converted from date picker, save into plist = %#", mdate );
self.saveDate = mdate;
//self.userDate = myDate.date;
// create dictionary with values in UITextFields
NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: userTitle, userMessage, saveDate, nil] forKeys:[NSArray arrayWithObjects: #"Title", #"Message", #"UserDate", nil]]; NSString *error = nil;
// create NSData from dictionary
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
// check is plistData exists
if(plistData)
{
// write plistData to our Data.plist file
[plistData writeToFile:plistPath atomically:YES];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Success" message:#"Your settings have been saved." delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok",nil];
[alert show];
}
else
{
NSLog(#"Error in saveData: %#", error);
//[error release];
}
viewWillAppear
- (void)viewWillAppear:(BOOL)animated {
[self.navigationController setNavigationBarHidden:YES];
[super viewWillAppear:animated];
// Data.plist code
// get paths from root direcory
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPath = [paths objectAtIndex:0];
// get the path to our Data/plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"Data.plist"];
// check to see if Data.plist exists in documents
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath])
{
// if not in documents, get property list from main bundle
plistPath = [[NSBundle mainBundle] pathForResource:#"Data" ofType:#"plist"];
}
// read property list into memory as an NSData object
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSString *errorDesc = nil;
NSPropertyListFormat format;
// convert static property liost into dictionary object
NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc];
if (!temp)
{
NSLog(#"Error reading plist: %#, format: %d", errorDesc, format);
}
NSLog(#"Plist Title: %#", [temp objectForKey:#"Title"]);
NSLog(#"Plist Message: %#", [temp objectForKey:#"Message"]);
NSLog(#"Plist date: %#", [temp objectForKey:#"UserDate"]);
userTitle.text = [NSString localizedStringWithFormat:#"%#", [temp objectForKey:#"Title"]];
userMessage.text = [NSString localizedStringWithFormat:#"%#", [temp objectForKey:#"Message"]];
//http://stackoverflow.com/questions/1070354/how-do-i-get-the-current-date-in-cocoa
NSDate* now = [[NSDate alloc] initWithTimeIntervalSinceNow:3600];
userCoundown.text = [NSString stringWithFormat:#"%#",now];
NSString *uDate = [[NSString alloc] init];
uDate = [temp objectForKey:#"UserDate"];
NSLog(#"Plist date in string - %#", uDate);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSDate *ddate = [dateFormatter dateFromString:uDate];
[dateFormatter setDateFormat:#"yyyy-MM-dd H:mm:ss Z"];
NSLog(#"Format date from Plist - %#", [dateFormatter stringFromDate:ddate]);
//NSLog(#"GMT format from Plist - %#", timeStamp);
//http://www.epochconverter.com/#
destinationDate = ddate;
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(updateLabel) userInfo:nil repeats:YES];
}
updatelabel
-(void)updateLabel {
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
int units = NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *components = [calendar components:units fromDate:[NSDate date] toDate:destinationDate options:0];
[datelabel setText:[NSString stringWithFormat:#"%d%c %d%c %d%c %d%c %d%c", [components month], 'm', [components day],
'd', [components hour], 'h', [components minute], 'm', [components second], 's']];
}
NSDate keeps time in GMT. If you have time zones you will have to specify them.
The question is not clear so this is not a complete answer but should provide some help with NSDate in a plist.
Here is an example of creating, writing and reading a plist with a NSDate:
NSDictionary *plistDict = [NSDictionary dictionaryWithObjectsAndKeys:
userTitle, #"Title",
userMessage, #"Message",
saveDate, #"UserDate",
nil];
[plistDict writeToFile:filePath atomically:YES];
NSDictionary *plistDictRead = [NSDictionary dictionaryWithContentsOfFile:filePath];
NSDate *dateRead = [plistDictRead objectForKey:#"UserDate"];
There is no need to convert the NSDate to a string and no need to use NSPropertyListSerialization.
Remember to create the NSDate and then output it with a valid timezone and calendar!
Check a similar question I answered in another post:
UIDatePicker return wrong NSDate
I would like to know how to save a selected date and time from a date picker into a plist.
NSMutableArray *userArray = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
NSMutableDictionary *dict = [userArray objectAtIndex:0];
NSDate *date = [NSDate date];
NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
[dateformatter setDateFormat:#"MM/dd/yyy hh:mm a"];
[dict setObject:[dateformatter stringFromDate:date] forKey:#"LastLocalDataUpdate"];
[userArray writeToFile:plistPath atomically:YES];
NSUserDefaults is good enough for what you're trying to do:
NSDate *theDate = [NSDate date];
[[NSUserDefaults standardUserDefaults] setObject:theDate forKey:#"Date"];
NSUserDefaults will do it just nicely.
i've been working on a tableview program and i have a function that processes several data from user preferences, and core-data. the program parses these things and returns a url adress. heres the code:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *serverAdress = [prefs stringForKey:#"serverAdress"];
serverAdress = [serverAdress stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd.MM.yyyy"];
NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];
[dateFormatter2 setDateFormat:#"dd.MM.yyyy HH:mm"];
NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
NSString *dateTimeString = [NSString stringWithFormat:#"%# %#",dateString,[dashboardParameters attribute1]];
NSTimeInterval dayInterval = [[dashboardParameters attribute2] intValue]*60*60*(-1);
NSDate *date2 = [[dateFormatter2 dateFromString:dateTimeString] addTimeInterval:dayInterval];
NSString *urlString =
[NSMutableString stringWithFormat:#"%#/webservices/service1.asmx/getHourlySales2?tarih2=%#&tarih1=%#&salesType=%#",
serverAdress,
dateTimeString,
[dateFormatter2 stringFromDate:date2],
[dashboardParameters itemOrder]
];
urlString = [urlString stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
return urlString;
Everything works great, i have no problem on retrieving data. But when i execute the code, i get this log output:
//server.dyndns.org/webservices/service1.asmx/getHourlySales2?tarih2=20.01.2011%2016:00&tarih1=19.01.2011%2016:00&salesType=Hepsi/webservices/service1.asmx/getHourlySales2?tarih2=21.01.2011%2022:00&tarih1=21.01.2011%2011:00&salesType=Hepsi
it has to be
//server.dyndns.org/webservices/service1.asmx/getHourlySales2?tarih2=20.01.2011%2016:00&tarih1=19.01.2011%2016:00&salesType=Hepsi
But strangely the program adds
/webservices/service1.asmx/getHourlySales2?tarih2=21.01.2011%2022:00&tarih1=21.01.2011%2011:00&salesType=Hepsi
by itself after the normal processing.
Also another important thing, the code runs normally when i remove
NSString *serverAdress = [prefs stringForKey:#"serverAdress"] from the code and enter serveradress manually.
Plase help , everything in the program works fine but im stuck with this problem.
Thanks for helping.
So what's in serverAdress before you add it to urlString. Looks as if serverAdress contains '//server.dyndns.org/webservices/service1.asmx/getHourlySales2?tarih2=20.01.2011%2016:00&tarih1=19.01.2011%2016:00&salesType=Hepsi'
I have the following code:
-(NSString *)tableView:(UITableView *)table titleForHeaderInSection:(NSInteger)section {
id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *sectionName = [sectionInfo name];
NSLog(#"sectionName %#", sectionName);
NSString *convDate = [dateFormatter stringFromDate: (NSDate *)sectionName];
NSLog(#"convDate %#", convDate);
return [NSString stringWithFormat:#"%#", [sectionInfo name]];
}
I am basically needing to convert the titleforheaderinsection which is a string date like "2009-12-04 00:00:00 +1100" to a nicer looking shorter string. So I have tried converting it using something like dateFormatter setDateStyle, but when i output the NSLog to console i get the following:
2009-12-22 09:42:10.156 app[94614:207] sectionName 2009-12-04 00:00:00 +1100
2009-12-22 09:42:10.157 app[94614:207] convDate (null
Obviously the convDate is not getting anything, but [sectionInfo name] should be a string. I have parsed it into its own NSString variable, so why cant i implement the dateFormatter on it?
A bit more information: I parse the date amongst other things earlier on, with the code snippet being:
if ([currentElement isEqualToString: #"date"]) {
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init] ;
[dateFormatter setDateFormat:#"eee, dd MMM yyyy"];
NSDate *convDate = [dateFormatter dateFromString:string];
if (self.isComment){
[currentComment setDate: convDate];
}else if (self.isPost)
NSLog(#"convDate is %#", convDate);
[currentPost setDate: convDate];
Now, when I debug this, essentially the raw string is "Sat, 27 Nov 2009 17:16:00 -800" but when i look at the convDate it comes out to be "2009-11-27 00:00:00 +1100". Not sure why, but in any case, thats what gets stored. I would have thought it would match the style i mentioned, so if i change the dateFormatter format to any other type, it would stuff up and convDate become nil.
Looking back at my postController: I have some snippets of interest:
- (NSFetchedResultsController *)fetchedResultsController {
if (fetchedResultsController == nil) {
NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease];
[fetchRequest setEntity:[NSEntityDescription entityForName:#"Post" inManagedObjectContext: ApplicationController.sharedInstance.managedObjectContext]];
NSArray *sortDescriptors = nil;
NSString *sectionNameKeyPath = #"date";
NSPredicate *pred = [NSPredicate predicateWithFormat:[NSString stringWithFormat:#"(PostSite.name like '%#')", self.site.name]];
[fetchRequest setPredicate:pred];
sortDescriptors = [NSArray arrayWithObject:[[NSSortDescriptor alloc]
initWithKey:#"date" ascending:NO] ];
[fetchRequest setSortDescriptors:sortDescriptors];
fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:
ApplicationController.sharedInstance.managedObjectContext
sectionNameKeyPath:sectionNameKeyPath cacheName:#"PostCache"];
}
return fetchedResultsController;
}
I am hoping to sort by date, and up in my code, in titleForHeaderInSection, format my string date to look more presentable.
Thanks guys
The reason you were getting unexpected behaviour is because during parsing you were setting the date format to
[dateFormatter setDateFormat:#"eee, dd MMM yyyy"];
which has no time information, which is why there was a time difference in the dates.
Also, during parsing you were setting convDate with
NSDate *convDate = [dateFormatter dateFromString:string];
which is storing an NSDate and crucially NSFetchResultsController is calling the description selector on convDate because it is not an NSString.
I'm not entirely sure why NSDateFormatter could not recognise the ISO date format.
The reason your code does not work is because
[sectionInfo name]
returns an NSString object, not an NSDate object, which is required by
[dateFormatter stringFromDate:];
You cannot simply cast an NSString to an NSDate.
Instead,
- (NSString *)tableView:(UITableView *)table titleForHeaderInSection:(NSInteger)section
{
id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
NSString *sectionName = [sectionInfo name];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *convDate = [dateFormatter stringFromDate:[dateFormatter dateFromString:sectionName]];
[dateFormatter release];
return convDate;
}
Also, don't autorelease an object unless there is a specific reason to do so.
I found the solution by going to http://iosdevelopertips.com/cocoa/date-formatters-examples-take-2.html and using http://unicode.org/reports/tr35/#Date_Format_Patterns as a guide, I debugged my code until i ensured that the variable is matched with the incoming string