Why does this function return the same value regardless of input? - objective-c

I have a method that formats a date string. I've encountered an issue where it returns only the formatted version of the first NSString I pass to it..
Code:
self.lastUpdatedLabel.text = [self convertTime:lastupdated];
self.expiryDate.text = [self convertTime:expiryDate];
Method
- (NSString *)convertTime:(NSString *)date{
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setDateFormat:#"HH:mm - dd/MM/yyyy"];
[timeFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"GMT"]];
date = [timeFormatter stringFromDate:[[NSDate alloc]init] ];
return date;
}
Both lastUpdatedLabel and expiry date are set to the value of expiryDate. Surely the method runs every time it is called, producing a different output as the input is different

It looks like you need to update your code to use your argument, date.
As people have mentioned in comments, you are using the current time, [[NSDate alloc] init] instead of the date that was passed in.
If lastUpdated and expiryDate are NSDates, then this will work.
- (NSString *)convertTime:(NSDate *)date{
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setDateFormat:#"HH:mm - dd/MM/yyyy"];
[timeFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"GMT"]];
return [timeFormatter stringFromDate:date];
}
If lastUpdated and expiryDate are NSStrings, which is what it looks like you have, then you need to convert your NSStrings to NSDates, using an NSDateFormatter that understands the format of the NSString that you have ... and then pass that NSDate to the code above to create a properly formatted string as output.

Related

Why is my NSDate not being formatted correctly?

I have a NSDate which is not being correctly formatted.
I have declared a UITextField in the .h :
#property (weak, nonatomic) IBOutlet UITextField *datetimeTextField;
Then I have a 3rd party UIPicker that picks a Date and inserts it in the mentioned TextField:
// Method to avoid diplaying the keyboard.
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
ActionSheetDatePicker *datePicker = [[ActionSheetDatePicker alloc]initWithTitle:#"Select Date and Time" datePickerMode:UIDatePickerModeDateAndTime selectedDate:[NSDate date] doneBlock:^(ActionSheetDatePicker *picker, id selectedDate, id origin) {
// As you can see here it's taking the correct (non-formatted) date
NSLog(#"Selected %#", selectedDate); // VALUE = Sat Nov 10 10:00:41 2018
//create a date formatter
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//set its format as the required output format
[formatter setDateFormat:#"dd-MM-yyyy HH:mm:ss"];
//get the output date as string
NSString *selectedDateString = [formatter stringFromDate:selectedDate];
self.datetimeTextField.text = selectedDateString;
// And here I get the value I want to store in Parse stored in datetimeTextField.text
NSLog(#"Selected After reformat %#", self.datetimeTextField.text); // VALUE = 10-11-2018 00:35:06
} cancelBlock:^(ActionSheetDatePicker *picker) {
} origin:self.view];
datePicker.minuteInterval = 5;
[datePicker showActionSheetPicker];
return NO;
}
My problem starts when I have to call an IBAction to store this NSDate in my Parse Cloud (I have a Date column that would only accept NSDate.
- (IBAction)createeventAction:(id)sender{
// Here I "catch" the value previously stored from the Picker.
NSString *dateString = datetimeTextField.text; //// 07-11-2018 22:00:42 (correct format)
// Here I convert the NSString into NSDate with the same formatting
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy HH:mm:ss"];
NSDate *date = [dateFormatter dateFromString:dateString];
// But for some reason, date prints incorrectly.
NSLog(#"DATE in here ====>>> %#", date); // Sat Nov 10 10:00:41 2018
}
Problem:
I would like to convert a NSString (datetimeTextField.text) to a NSDate without losing the format.
EDIT 1:
I had consulted the accepted answer from this question How to convert NSStrings to NSDate but for some reason, it does not work for me.
EDIT 2:
To make it more clear:
Code to convert NSDate to NSString.
// We have a date (not formatted) => Sat Nov 10 10:00:41 2018
//create a date formatter
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd-MM-yyyy HH:mm:ss"];
NSString *selectedDateString = [formatter stringFromDate:selectedDate];
self.datetimeTextField.text = selectedDateString;
// Date formatted => 10-11-2018 00:35:06
Code to convert NSString back to NSDate:
NSString *dateString = datetimeTextField.text; // 10-11-2018 10:00:41 (correct format)
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy HH:mm:ss"];
NSDate *date = [dateFormatter dateFromString:dateString];
NSLog(#"DATE in here ====>>> %#", date); // Sat Nov 10 10:00:41 2018 (not formatted. WHY?)
Well thats the thing. I need to have a NSDate because I am storing dates.
You seem to misunderstand the difference between NSDate and what you get back from NSDateFormatter. NSDate is just a class that stores a date in no particular format -- it stores the information inside the object. If you want to display the date in a particular format, you need to create a string from the date, and you use NSDateFormatter to do convert your date into a string that expresses the date in the format you need.
If you print the date to the console using NSLog(), like:
NSLog("My date is %#", myDate);
then NSLog will just use the date's description method, which gives you a sort of default expression of the date. If you want to log the date in some specific format, you'll need to set up a date formatter with that format and then use it:
NSLog("My formatted date is %#", [myFormatter stringFromDate:myDate]);
In the end it turned out that my code was fine. Only thing is that I did not notice that the Date was declared as String in Parse instead of as Date.

Date not displayed properly in the nib file

I have a string with value #"15/11/13". I need to display the same on the label in the nib file.
I am using the following code to display it
NSDateFormatter * df1 = [[NSDateFormatter alloc] init];
[df1 setDateFormat:#"yyyy-mm-dd"];
[df1 setDateStyle:NSDateFormatterShortStyle];
[df1 setTimeStyle:NSDateFormatterNoStyle];
[profile1 setLastPromotionDate:[df1 dateFromString:#"11/11/13"]];
Profile1 is a different class which has lastPromotonDate of type NSDate.
In the nib file I have a outlet to display date which is bound to lastPromotionDate.
When I run the app, the date displayed is Monday, 11 November 2013 12:00:00 AM India Standard Time.
Can I know what is the mistake here? What has to be done so the date displays in this format : 11/11/13
Try this:-
NSString *dateStr=#"11/11/13";
NSDateFormatter *format=[[[NSDateFormatter alloc]init]autorelease];
[format setDateFormat:#"dd/mm/yy"];
NSDate *dt=[format dateFromString:dateStr];
NSString *str=[format stringFromDate:dt];
NSLog(#"%#",str);
NSString *str = #"15/11/13";
// here we create NSDateFormatter object for change the Format of date..
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init] ;
// here set format of date which is in your output date (means above str with format)
[dateFormatter setDateFormat:#"yy/mm/dd"];
// here you can fetch date from string with define format
NSDate *date = [dateFormatter dateFromString: str];
dateFormatter = [[NSDateFormatter alloc] init] ;
// here set format which you want..
[dateFormatter setDateFormat:#"dd/mm/yy"];
NSString *convertedString = [dateFormatter stringFromDate:date];
//here convert date in NSString
NSLog(#"Converted String : %#",convertedString);
rofile1.text = convertedString;
Why not just set it as:
NSString *str = #"15/11/13";
[label setStringValue: str];
UPDATE:
To convert this string to NSDate of the same format use:
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"dd/mm/yy"];
NSDate * date = [df dateFromString:str];
To get back the string value of date from NSDate use:
NSString *dateStr = [df stringFromDate: date];
Also you may use this dateStr to set you label text as
[label setStringValue: dateStr];
or bind the label to "dateStr". (Do not bind it to "date" of NSDate type, I think this is where you are going wrong).
Use "date" variable that is of NSDate type for your server requests.
UPDATE:
Since you are binding your label to NSDate value, it displays the complete date in the way it is present in NSDate. To retrieve the value of that NSDate in your custom format, you need to use NSDateFormatter that will write the part of NSDate that we need in our format to a NSString.
Also if we convert a NSString to NSDate, it doesn't mean that date formatter will save the NSDate in our custom format, the format of the date formatter specify the format of our string so that NSDate could read the correct date from our custom formatted string. But NSDate will always save the date value in its own format.
We have something called DateFormatter under objects in the library. We can drag and drop that under the text cell if the label in the list view of the nib.
This data formatter converts the date format to string value which is used to display in the UI.

Objective-C – NSDateFormatter dateFromString ignore time

If I'm not interested in the time can I ignore it? I.e I have a date string that looks like this #"2012-12-19T14:00:00" but I'm only interested in getting the date (2012-12-19) but if I set NSDateFormatter like [dateFormatter setDateFormat:#"yyyy-MM-dd"]; it will return me a nil NSDate.
An NSDate object will always contain a time component as well, as it is representing a point in time — from this perspective one could argue the name NSDate is misleading.
You should create a date formatter for creating dates from string, set the time to the start of the day and use a second date formatter to output the date without time component.
NSString *dateString = #"2012-12-19T14:00:00";
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss"];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateStyle:NSDateFormatterShortStyle];
[outputFormatter setTimeStyle:NSDateFormatterNoStyle];
NSDate *date = [inputFormatter dateFromString:dateString];
//this will set date's time components to 00:00
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit
startDate:&date
interval:NULL
forDate:date];
NSString *outputString = [outputFormatter stringFromDate:date];
NSLog(#"%#", outputString);
results in
19.12.12
while the format — as it is chosen by styling — will be dependent of your environment locale
all date string returns 10 characters for the date, what i mean is the date of todayy will be 2012-11-19
you can easily substring the date and use it as you want:
Example :
NSString* newDate = #"";
newDate = [[NSDate date]substringToIndex:10];
the out put will be : 2012-11-19

current Date and Time - NSDate

I need to display the current Date and Time.
I have used ;
NSDate *currentDateNTime = [NSDate date];
I want to have the current date and time (Should display the system time and not GMT time).
The output should be in a NSDate format and not NSString.
for example;
NSDate *currentDateNTime = [NSDate date];
// Do the processing....
NSDate *nowDateAndTime = .....; // Output should be a NSDate and not a NSString
Since all NSDate is GMT referred, you probably want this:
(don'f forget that the nowDate won't be the actual current system date-time, but it's "shifted", so if you will generate NSString using NSDateFormatter, you will see a wrong date)
NSDate* currentDate = [NSDate date];
NSTimeZone* currentTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
NSTimeZone* nowTimeZone = [NSTimeZone systemTimeZone];
NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:currentDate];
NSInteger nowGMTOffset = [nowTimeZone secondsFromGMTForDate:currentDate];
NSTimeInterval interval = nowGMTOffset - currentGMTOffset;
NSDate* nowDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:currentDate];
Every moment in time is the same moment in time everywhere around the world —- it is just expressed as different clock times in different timezones. Therefore, you can't change the date to some other date that represents the time in your timezone; you must use an NSDateFormatter that you feed with the timezone you are in. The resulting string is the moment in time expressed in the clock time of your position.
Do all needed calculations in GMT, and just use a formatter for displaying.
Worth reading
Does [NSDate date] return the local date and time?
Some useful resources for anyone coming to this more recently:
Apple date and time programming guide do read it if you're doing anything serious with dates and times.
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/DatesAndTimes/DatesAndTimes.html#//apple_ref/doc/uid/10000039i?language=objc
Useful category on NSDate with lots of utilities does allow a ~new~ date to be generated based on an existing date.
https://github.com/erica/NSDate-Extensions
There's also a swift version of the category
https://github.com/erica/SwiftDates
You need an NSDateFormatter and call stringFromDate this method to get a string of your date.
NSDateFormatter *dateformater = [[NSDateFormatter alloc] init];
[dateformater setDateFormat:#"yyyyMMdd,HH:mm"];
NSString *str = [dateformater stringFromDate: currentDateNTime];
use this method
-(NSDate *)convertDateToDate:(NSDate *) date
{
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
NSDate *nowDate = [[[NSDate alloc] init] autorelease];
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
[formatter setDateFormat:#"yyyy-MM-d H:m:s"];
NSString * strdate = [formatter stringFromDate:date];
nowDate = [formatter dateFromString:strdate];
return nowDate;
}
this may return you what you want.
i hope you this may help you.

iPhone simple method definition and calling the current date/time

I'm very new to iPhone development, and I'm trying to write a function which will accept one parameter, and return the current date/month and store it in a variable.
But I'm getting a (null) value with NSLog.
Method:
-(NSString *) getNowDateMonth:(NSString *)type {
NSDate *now = [[NSDate alloc] init];
if (type==#"month") {
NSDateFormatter *monthFormat = [[NSDateFormatter alloc] init];
[monthFormat setDateFormat:#"MM"];
NSString *theMonth = [monthFormat stringFromDate:now];
[monthFormat release];
return theMonth;
} else if (type==#"day") {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd"];
NSString *theDate = [dateFormat stringFromDate:now];
//int setDate = theDate;
[dateFormat release];
return theDate;
}
[now release];
return NULL;
}
Calling the function to get value:
NSString *month = [self getNowDateMonth:#"month"];
NSLog(#"%#", month);
Am I going about this the right way?
First of all, compare the strings using [#"month" isEqualToString:type], because two strings containing the same text ("month") may not be equal by the == operator. == checks if they're the same string object, not strings object with the same contents.
Second of all, you're leaking the date when returning the month or day (not releasing now). You should use [NSDate date]; instead of [[NSDate alloc] init].
To sum up, a suggested better version of this method would be:
-(NSString *) getNowDateMonth:(NSString *)type {
NSDate *now = [NSDate date];
if ([#"month" isEqualToString:type]) {
NSDateFormatter *monthFormat = [[NSDateFormatter alloc] init];
[monthFormat setDateFormat:#"MM"];
NSString *theMonth = [monthFormat stringFromDate:now];
[monthFormat release];
return theMonth;
} else if ([#"day" isEqualToString:type]) {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd"];
NSString *theDate = [dateFormat stringFromDate:now];
[dateFormat release];
return theDate;
} else {
return nil;
}
}
Also, there are a few other points that can be taken into consideration to improve this method:
do not use NSString as type; use an enum
do not allocate NSDateFormatter on each call to the method; instead use a static variable in the method
You want to use NSDateComponents to reliably and easily extract unit information i.e. month, day, week etc from an NSDate.
See Date and Time Programming Guide for Cocoa.
Dates are a deceptively complex programing problem so Cocoa has a fully developed set of classes for dealing with them. However, the learning curve is a bit steep.