Convert string date time from one region to another in Objective-C - objective-c

I have a string date in UK format: 19 March 2014 10:17 and I want to be able to convert it to US format as a string like so: March 19, 2014, 10:17 AM, whenever the user changes region on their iPhone. This is what I have tried so far:
NSString * lastResetDateTime = [[NSUserDefaults standardUserDefaults] objectForKey:LAST_STATS_REST_DATETIME]; //date I want to convert
if(lastResetDateTime != nil){
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSDate* lastResetDate = [dateFormatter dateFromString:lastResetDateTime];
self.lastResetDateTime.text = [dateFormatter stringFromDate:lastResetDate];
}
However, lastResetDate is null, is there any other way to use the formatter for that type of date ?

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.

NSDateFormatter produces null result Objective-C

So I have this string date
"2017-07-25T11:02:00.000Z"
I want to format this date so that I can assign it to my date picker
Below is my code
//Set the date
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MMM d, yyyy"];
NSDate *dateFromString = [dateFormatter dateFromString:self.userDefaultQuotationModel.dateTime];
[self.quotationDatePicker setDate:dateFromString];
however, if I set the date format as #"yyyy-MM-dd'T'HH:mm:ss.SSSZZZ", it gives me the correct result based on the format. But afterwards, I can't assign this date to the date picker.
I set the date format as #"MMM d, yyyy" because I am looking for the the nearest format as Date Picker's
my Date picker format is Jul 25 2017. I get the date format from this following website
http://nsdateformatter.com/
The *dateFromString does not contain any value after the dateFromString function, which is nil
I have been searching regarding this topic but couldn't find any. What am I missing here? thank you
NSString *strInputDateString = #"2017-07-25T11:02:00.000Z";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSSZZZ"];
//Set new dateFormate
NSDate *date1 = [dateFormat dateFromString:strInputDateString];
[dateFormat setDateFormat:#"MMM d, yyyy"];
NSString *strOutputDateString = [dateFormat stringFromDate:date1];
NSLog(#"%#",strInputDateString);
NSLog(#"%#",strOutputDateString);

Need to convert custom timestamp to different format in Objective-C iOS

I have a string "2012-06-04" and am having a hard time converting it to: June 4, 2012.
Is there a quick way to transform this? I come from a ruby world where you would convert everything to seconds and that back out to the format you need it. Is there a reference that shows how to do that?
Thanks
One way to do so is to convert the string to an NSDate using the NSDateFormatter with the 2012-06-04 format, and then convert the NSDate back to a string using the June 4, 2012 format:
NSString* input = #"2012-06-04";
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyy-MM-dd"];
NSDate* date = [df dateFromString:input];
[df setDateFormat:#"MMMM d, yyyy"];
return [df stringFromDate:date];
The format string's syntax is described in UTS #35.
Something like
NSDateFormatter *fromDateFormatter = [[NSDateFormatter alloc] init];
fromDateFormatter.dateFormat = #"yyyy-MM-dd";
NSDate *date = [fromDateFormatter dateFromString:#"2012-06-04"];
NSLog(#"%#", date);
NSDateFormatter *toDateFormatter = [[NSDateFormatter alloc] init];
toDateFormatter.dateFormat = #"MMMM d, yyyy";
NSString *toDate = [toDateFormatter stringFromDate:date];
NSLog(#"%#", toDate);
#=> 2012-05-30 20:51:12.205 Untitled[1029:707] 2012-06-03 23:00:00 +0000
#=> 2012-05-30 20:51:12.206 Untitled[1029:707] June 4, 2012
To work this out you can use Apple's class references NSDateFormatter and other sources like this IPHONE NSDATEFORMATTER DATE FORMATTING TABLE and some trial and error

Use (Billy Meltdown) NSDate-helper methods to convert Unix timestamp and display?

I would like to convert a Unix timestamp e.g 1315401371 stored as a NSString into a date format of 23:00 12 October 2011.
There are a number of similar questions being ask in relation to this however I wish to use billymeltdown / nsdate-helper methods
I have imported the 2 files (.h and .m) into my project, but have not manage to get further than that.
There is documentation, which I have read, however I am still very new to objective C and do not understand how I actual use the libraries.
Thanks in Advance.
You should use NSDateFormatter
NSTimeInterval timestamp = 1315401371;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timestamp];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm dd MMMM yyyy"]; // use one d for 7 October instead of 07 October
// For english month names
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
[dateFormatter setLocale:usLocale];
[usLocale release];
NSString *dateString = [dateFormatter stringFromDate:date];
[dateFormatter release];

How to Format Unknown Date Format in Objective-C

I've probably overlooked something simple, but I can't figure out how to convert a specific date format in Objective-C. I'm receiving dates in this format:
Sun, 10 Oct 2010 01:44:00 +0000
And I need to convert it to a long format with no time, like this:
October 10, 2010
I've tried using NSDateFormatter, but when I try to get a date from the string, it always comes back nil. I've tried it this way:
NSString *dateFromData = [articleData objectAtIndex:5];
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
NSDate *date = [dateFormatter dateFromString:dateFromData];
NSString *formattedDateString = [dateFormatter stringFromDate:date];
The date string always comes back nil. Am I missing something simple here?
This is the code I got to work, couldn't get the other format string to function
NSString *dateFromData = #"Sun, 10 Oct 2010 01:44:00 +0000";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"EEE, dd MMM yyyy hh:mm:ss zzzz"];
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
[dateFormatter setTimeZone:gmt];
NSDate * date = [dateFormatter dateFromString:dateFromData];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
NSString *formattedDateString = [dateFormatter stringFromDate:date];
The problem is you need to use two date formatters. One to parse the original format and one to produce the desired output. You also can't use the LongStyle date format as it doesn't match your input style.
NSDateFormatter *df = [[NSDateFormatter alloc] initWithDateFormat:#"%a, %d %b %Y %H:%M:%S %z"
allowNaturalLanguage:false];
NSDate *d = [df dateFromString:#"Sun, 10 Oct 2010 01:44:00 +0000"];
NSDateFormatter *df2 = [[NSDateFormatter alloc] initWithDateFormat:#"%B %d, %Y"
allowNaturalLanguage:false];
[df2 stringFromDate:d]
(Note, I wrote this code in MacRuby and ported it back to Objective-C so there maybe syntax errors.)
irb(main):001:0> df = NSDateFormatter.alloc.initWithDateFormat("%a, %d %b %Y %H:%M:%S %z", allowNaturalLanguage:false)
=> #<NSDateFormatter:0x20021b960>
irb(main):002:0> d = df.dateFromString("Sun, 10 Oct 2010 01:44:00 +0000")
=> #<NSCalendarDate:0x2002435e0>
irb(main):004:0> df2 = NSDateFormatter.alloc.initWithDateFormat("%B %d, %Y", allowNaturalLanguage:false)
=> #<NSDateFormatter:0x20026db60>
irb(main):005:0> df2.stringFromDate(d)
=> "October 09, 2010"