Why is my NSDate not being formatted correctly? - objective-c

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.

Related

Converting user custom date format string to nsdate?

Suppose, an user has set a custom date format in the Languages and Region section of System Preferences. Screenshot - http://imgur.com/gallery/dMy8u
I have this date in NSString representation (eg - #"201603/11") and I'd like to convert it to my own date format i.e. "MM/dd/yyyy". I'm using the following code:
NSDateFormatter *formatter = [NSDateFormatter new];
formatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:#"MM/dd/yyyy"
options:0
locale:[NSLocale systemLocale]];
[formatter setDateStyle:NSDateFormatterShortStyle];
NSDate *localDate = [formatter dateFromString:#"201603/11"];
But localDate always returns nil.
In short, my NSString representation is 201603/11 (format set by user), and I'd like to get this in NSDate representation.
// User Date format
NSDateFormatter *userFormatter = [NSDateFormatter new];
[userFormatter setDateFormat: #"yyyyMM/dd"];
NSDate *localDate = [userFormatter dateFromString:#"201610/31"];
NSLog(#"%#",localDate); //You will get, Year: 2016, Month:10, Day: 31
// The date format you want
NSDateFormatter *myFormatter = [NSDateFormatter new];
[myFormatter setDateFormat: #"MM/dd/yyyy"];
// Get date string from your local date object
NSString *myDateString = [myFormatter stringFromDate:localDate];
NSLog(#"%#",myDateString); //You will get a string, 10/31/2016

Not getting NSDate from string

I have following date in string formate "date string : 2014-09-28 17:30:00"
Now, I want to convert it into NSDate.
I have use following code for this.
NSString *date = #"2014-09-28 17:30:00";
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter1 dateFromString:date];
NSLog(#"date from string: %#", dateFromString);
I got the following output.
date from string: 2014-09-28 12:00:00 +0000
So, Here Time is changed.
Please tell me, How can I convert into NSDate. What I am missing here?
When you pass an NSDate object into NSLog, it will print the NSDate in GMT time, which may not be your timezone (and why you were getting 12:00 instead of 17:30), this would also cause the output of your NSLog statement to be different for people who are running your code in different timezones, so what you want to do is call the [NSDateFormatter stringFromDate:] method if you want to keep your specified time from your date object:
So replace this line of code:
// Will print out GMT time by default (+0000)
NSLog(#"date from string: %#", dateFromString);
With this line:
// Will honor the timezone of your original NSDate object:
NSLog(#"date from string: %#", [dateFormatter1 stringFromDate:dateFromString]);
And that should print out the value you were hoping for.
// --------------------------//
Note: It is important to understand that NSDate objects do not have any concept of timezones, so it is up to the developer to manage and track their timezones with the provided platform methods.
On iOS, you can look into using this class:
NSTimeZone, which can help you manage/assign your timezone(s) on iOS platforms.
If you are developing for OSX, you can assign a timezone and locale with this method: -descriptionWithCalendarFormat:timeZone:locale:. (Sadly, this method is OSX-only)
Hope that helps.
There is a time zone component attached to your log at the end that means the date is converted to the specified time zone..here greenwhich mean time
So converting into your time locale can give you the right value you inserted
In your first string add +0000 to the end and check again you can see the value is the same you get.ie the conversion is done on the GMT format
visit https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html
This documentation provides you how to convert NSString to date.
this code is provided by apple documentation.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:162000];
NSString *formattedDateString = [dateFormatter stringFromDate:date];
NSLog(#"formattedDateString: %#", formattedDateString);
// Output for locale en_US: "formattedDateString: Jan 2, 2001".
To make string as date
NSString *formattedDateString = [dateFormatter stringFromDate:date];
stringFromDate:
Returns a string representation of a given date formatted using the receiver’s current settings.
what you had used
dateFromString:
Returns a date representation of a given string interpreted using the receiver’s current settings.

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.

Date with month name date, year in objective-c

I have a date string formatted as "September 10, 2013". How can I convert this representation into a format such as "yyyy/mm/dd".
NSString *strDate = #"September 10, 2013";
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df dateFromString:strDate];
NSDate *date = [df dateFromString:strDate];
[df setDateFormat:#"yyyy/mm/dd"];
NSString* temp = [[NSString alloc] init];
temp = [df stringFromDate:date];
NSLog(#"date i required %#", temp);
temp object is null here.
Thanks in advance.
Let's rework your original code, and discuss it as well:
NSString *strDate = #"September 10, 2013";
NSDateFormatter *df = [[NSDateFormatter alloc] init];
For the input you're attempting to parse, you've got to provide a format string for your date formatter. If you don't, the date formatter is going to use defaults that are determined by the settings in your Date & Time control panel. Not only do these settings vary from locale to locale, they're subject to whatever changes the user may have effected. Another way of putting it is that they might not match the format of the date string you're attempting to convert.
You also don't want to rely on predefined styles such as NSDateFormatterShortStyle, NSDateFormatterMediumStyle or NSDateFormatterLongStyle. They're meant for date display (if you're willing to accept the Date & Time control panel settings), not for parsing.
There's a document you should consult, which is Unicode Technical Standard #35. Look in the table labeled "Date Field Symbol Table." Based on the information presented there (and your input), you'd set up your date converter to parse with a format string like this one:
[df setDateFormat:#"MMMM dd, yyyy"];
Now you can use your date formatter to parse your date string, and it'll work:
NSDate *date = [df dateFromString:strDate];
From this point onward, you're looking pretty good (though I've removed a superfluous line or two throughout all of this):
[df setDateFormat:#"yyyy/MM/dd"];
NSString *temp = [df stringFromDate:date];
NSLog(#"date i required %#", temp);
Best wishes to you in your endeavors.
You can use the NSDateFormatterclass -- look at the stringFromDate and dateFromString methods.
UPDATE: you have a couple of problems -- first, you need to tell the formatter what the initial format should be. Second, you have a format problem with the second format string -- 'm' is minutes, 'M' is months. You should review the documentation here. Here is an example:
NSString *strDate = #"September 10, 2013";
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateStyle:NSDateFormatterLongStyle];
[df dateFromString:strDate];
NSDate *dat = [df dateFromString:strDate];
[df setDateFormat:#"yyyy/MM/dd"];
NSString* t = [df stringFromDate:dat];
NSLog(#"date i required %#", t);

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