Currently I have two NSDateFormatters in my app and I want to somehow "combine" them so I only have, since they're parsing the same date.
I have a NSObject called UpcomingReleases, thats where all my JSON info gets stored.
UpcomingRelease.h
- (NSString *) formattedDate;
UpcomingRelease.m
- (NSString *) formattedDate {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSDate *readableDate = [dateFormatter dateFromString:self.release_date];
[dateFormatter setDateFormat:#"MMMM dd"];
return [dateFormatter stringFromDate:readableDate];
}
My UICollectionViewController (UpcomingReleasesViewController.m)
if([upcomingReleaseDictionary objectForKey:#"release_date"] != NULL)
{
NSString *readableDate = [upcomingReleaseDictionary objectForKey:#"release_date"];
UpcomingRelease *upcoming = [[UpcomingRelease alloc] init];
upcoming.release_date = readableDate;
cell.release_date.text = [NSString stringWithFormat:#"%#", upcoming.formattedDate];
}
My detailedViewController (ReleaseViewController.m)
(_singleRelease is a NSDictionary)
- (void)viewDidLoad
{
[super viewDidLoad];
if([_singleRelease objectForKey:#"release_date"] != NULL)
{
NSString *readableDate = [_singleRelease objectForKey:#"release_date"];
UpcomingRelease *singleRelease = [[UpcomingRelease alloc] init];
singleRelease.release_date = readableDate;
self.release_date.text = [NSString stringWithFormat:#"%#", singleRelease.formattedDate];
}
}
This was working fine, until I added a share on twitter action and I had to add another NSDateFormatter so it could show the readable date inside the tweet (I would get an error saying "No visible interface for ReleaseViewController declares the selected 'formattedDate'" otherwise).
- (NSString *) formattedDate:(NSString *)jsonDateString {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSDate *readableDate = [dateFormatter dateFromString:jsonDateString];
[dateFormatter setDateFormat:#"MMMM dd"];
return [dateFormatter stringFromDate:readableDate];
}
#pragma mark - Share on twitter
- (IBAction)shareOnTwitter:(id)sender {
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
{
SLComposeViewController *tweetSheet = [SLComposeViewController
composeViewControllerForServiceType:SLServiceTypeTwitter];
NSString *formattedDate = [self formattedDate:[_singleRelease objectForKey:#"release_date"]];
[tweetSheet setInitialText:[NSString stringWithFormat:#"%#", formattedDate]];
[self presentViewController:tweetSheet animated:YES completion:nil];
}
}
How can I combine both these NSDateFormatters into one? They're both parsing the same string in the same way (also if there's a better way to show the formattedDate string than the one I'm currently doing would be great).
This is how my JSON shows the date string:
release_date: "2013-11-16T00:00:00.000Z"
Thanks.
As #Hot Licks says:
Make the date formatter a class method:
+ (NSString *) formattedDate:(NSString *)jsonDateString {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSDate *readableDate = [dateFormatter dateFromString:jsonDateString];
[dateFormatter setDateFormat:#"MMMM dd"];
return [dateFormatter stringFromDate:readableDate];
}
Put it in a utility class and use it in both cases. In the first case just pass in self.release_date.
Related
I have 4 UITextfileds, start date, start time and end date, end time. Then I'm sending my date and time into my UTC function, but it's returning null.
NSString *str1 = _startDateField.text;
str1 = [str1 stringByAppendingString:#" "];
str1 = [str1 stringByAppendingString:_startTimeField.text];
NSLog(#"str1 : %#", str1);
NSString *str2 = _endDateField.text;
str2 = [str2 stringByAppendingString:#" "];
str2 = [str2 stringByAppendingString:_endTimeField.text];
NSLog(#"str2 : %#", str2);
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd-MMM-yyyy HH:mm"];
NSDate *date1 = [dateFormat dateFromString:str1];
NSDate *date2 = [dateFormat dateFromString:str2];
NSLog(#"%#", date1);
NSLog(#"%#", date2);
NSString *startTime = [self getUTCFormateDate:date1];
NSString *endTime = [self getUTCFormateDate:date2];
NSLog(#"str1 : %#", startTime);
NSLog(#"str2 : %#", endTime);
Coverting to UTC format:
-(NSString *)getUTCFormateDate:(NSDate *)localDate {
NSLog(#"%#", localDate);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateFormat:#"dd-MMM-yyyy HH:mm"];
NSString *dateString = [dateFormatter stringFromDate:localDate];
NSLog(#"%#", dateString);
return dateString;
}
I want to read the date and time from my text fields and convert them into UTC format.
your code is fine and correct, I added the defaultTimeZone for get the time zone and subtract the time to utc time. I got the output.
check this
NSString *str1 = #"26-Nov-2019";
str1 = [str1 stringByAppendingString:#" "];
str1 = [str1 stringByAppendingString:#"9:35 am"];
NSLog(#"str1 : %#", str1);
NSString *str2 = #"26-Nov-2019";
str2 = [str2 stringByAppendingString:#" "];
str2 = [str2 stringByAppendingString:#"11:59"];
NSLog(#"str2 : %#", str2);
// Convert string to date object
NSDate *date1 = [self getUTCDate:str1];
NSDate *date2 = [self getUTCDate:str2];
NSLog(#"date1 %#", date1);
NSLog(#"date2 %#", date2);
NSString *startTime = [self getUTCFormateDate:date1];
NSString *endTime = [self getUTCFormateDate:date2];
NSLog(#"str1 : %#", startTime);
NSLog(#"str2 : %#", endTime);
-(NSDate *)getUTCDate:(NSString *)currentDate {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd-MMM-yyyy HH:mm"];
NSDate *date1 = [dateFormat dateFromString:currentDate];
if (date1 == nil) {
[dateFormat setDateFormat:#"dd-MMM-yyyy hh:mm a"];
date1 = [dateFormat dateFromString:currentDate];
}
return date1;
}
-(NSString *)getUTCFormateDate:(NSDate *)localDate {
NSLog(#"%#", localDate);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateFormat:#"dd-MMM-yyyy HH:mm"];
NSLocale *twelveHourLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
dateFormatter.locale = twelveHourLocale;
NSTimeInterval timeZoneoffset = [[NSTimeZone defaultTimeZone] secondsFromGMT];
NSTimeInterval utcTimeInterval = [localDate timeIntervalSinceReferenceDate] - timeZoneoffset;
NSDate *utcCurrentDate = [NSDate dateWithTimeIntervalSinceReferenceDate:utcTimeInterval];
NSString *dateString = [dateFormatter stringFromDate:utcCurrentDate];
NSLog(#"dateString %#", dateString);
return dateString;
}
I want to connect and pass the action from ViewController to NSObject class file. In my viewcontroller, there is UISwitch Button and if I switch I want to work it in NSObject class file.
When switch is ON from viewcontroller (UIView) then the action have to work in NSObject class file.
I'm coding with Objective-C.
Here is my ViewController.m and I did this in only ViewController file. Not connected to NSOBject class file.
- (void)viewDidLoad{
[super viewDidLoad];
//UISwitch work at viewDidload
[self.mySwitch addTarget:self
action:#selector(stateChanged:) forControlEvents:UIControlEventValueChanged]; }
- (void)stateChanged:(UISwitch *)switchState{
NSLog(#"current calendar: %#", [[NSCalendar currentCalendar] calendarIdentifier]);
//get the date today
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setCalendar:[NSCalendar currentCalendar]];
NSString *dateToday = [formatter stringFromDate:[NSDate date]];
NSLog(#"Today Date is: %#", [NSDate date]);
self.myLabel.text=dateToday;
if ([switchState isOn]) {
//[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US#calendar=japanese"]];
[formatter setCalendar:[[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierJapanese]];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSString *dateToday = [formatter stringFromDate:[NSDate date]];
UILabel *dtDate = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320.0f, 20.0f)];
[dtDate setText:dateToday];
self.myLabel.text =dateToday;
NSString *locale = [[NSLocale currentLocale] localeIdentifier];
NSLog(#"current date is: %#", dateToday);
NSLog(#"current locale: %#", locale);
} else {
//[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US"]];
[formatter setCalendar:[NSCalendar autoupdatingCurrentCalendar]];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSString *dateToday = [formatter stringFromDate:[NSDate date]];
UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320.0f, 20.0f)];
[myLabel setText:dateToday];
self.myLabel.text =dateToday;
// NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// [formatter setDateStyle:NSDateFormatterMediumStyle];
NSString *locale = [[NSLocale currentLocale] localeIdentifier];
NSLog(#"current locale: %#", locale);
NSLog(#"%#", [formatter stringFromDate: [NSDate date]]);
}
}
If you need just an action then use class methods else create a global variable or a notification observer in NSObject extended class when you get call back from the switch.
- (void)callback:(id)sender
{
[MyObject switchState:sender.state];
}
I am new to iOS. I am making an alarm application and I want to implement the repeat functionality. I search a lot and didn't understand much how to do this. I know it is done by notification method. I am stuck with it . Please anyone tell me the solution. Here is my code when user save the alarm.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.timeZone = [NSTimeZone defaultTimeZone];
NSLog(#"dateformater %#",dateFormatter);
dateFormatter.timeStyle = NSDateFormatterShortStyle;
NSString * dateTimeString = [dateFormatter stringFromDate:timePicker.date];
NSLog(#"date time string %#",dateTimeString);
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:NSLocaleIdentifier]];
//[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
datesArray = #[[dateFormatter stringFromDate:self.timePicker.date]];
NSLog(#"dates array is %#",datesArray);
[datesArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
NSArray * repeatDays = [repeatResult componentsSeparatedByString:#","];
for (NSString * days in repeatDays)
{
if ([days isEqualToString:#"Sun"])
{
[self getDateOfSpecificDay:1];
}
if ([days isEqualToString:#"Mon"])
{
[self getDateOfSpecificDay:2];
}
if ([days isEqualToString:#"Tue"])
{
[self getDateOfSpecificDay:3];
}
if ([days isEqualToString:#"Wed"])
{
[self getDateOfSpecificDay:4];
}
if ([days isEqualToString:#"Thu"])
{
[self getDateOfSpecificDay:5];
}
if ([days isEqualToString:#"Fri"])
{
[self getDateOfSpecificDay:6];
}
if ([days isEqualToString:#"Sat"])
{
[self getDateOfSpecificDay:7];
}
}
}];
AlarmObject * alarm = [[AlarmObject alloc] init];
alarm.repeatData = repeatResult;
alarm.clockDate = dateTimeString;
[self.delegate alarmSetting:alarm];
[self scheduleLocalNotificationWithDate:timePicker.date];
[self.navigationController popViewControllerAnimated:YES];
and here is my scheduledLocalNotification mehtod
-(void) scheduleLocalNotificationWithDate:(NSDate *)fireDate
{
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
localNotif.alertBody = #"Time to wake Up";
localNotif.alertAction = #"Show me";
localNotif.soundName = #"Tick-tock-sound.mp3";
localNotif.applicationIconBadgeNumber = 1;
localNotif.repeatInterval = NSCalendarUnitWeekOfYear;
NSLog(#"%#",[NSDate date]);
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];`
I'm stuck with it from past 4 days. I know my question is duplicate but I am not sure how implement that logic. Thanks in advance.
Change the
dateFormatter.timeZone = [NSTimeZone defaultTimeZone];
to
dateFormatter.timeZone = [NSTimeZone localTimeZone];
and check out this tutorial for repeat fucntionailty.
When I go to a viewcontroller in my app, I have two date pickers. Both of which have labels, and if either one is moved they update accordingly.
The start date is set to automatically be today's date. While it saves to Core Data just fine it doesn't display in the label unless I change it to a different day.
Basically when I load that screen the label should have today's date, and change if I change it in the date picker.
I figure it's something simple overlooking, but I can't figure out what it is, any help would be appreciated.
- (void)viewDidLoad
{
[super viewDidLoad];
svos = self.scrollView.contentOffset;
[self.startDate addTarget:self action:#selector(datePickerChanged:) forControlEvents:UIControlEventValueChanged];
[self.endDate addTarget:self action:#selector(datePickerChanged1:) forControlEvents:UIControlEventValueChanged];
AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
if(!appDelegate.dateProductionDroneStartDate)
[self.startDate setDate:[NSDate date]];
else
{
[self.startDate setDate:appDelegate.dateProductionDroneStartDate];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MM-dd-yyyy "];
NSString *strDate = [dateFormatter stringFromDate:self.startDate.date];
self.productionDroneStartDate.text = strDate;
}
NSDate *now = [NSDate date];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:1];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *newDate2 = [gregorian dateByAddingComponents:components toDate:now options:0];
if(!appDelegate.dateProductionDroneEndDate)
[self.endDate setDate:newDate2];
else
{
[self.endDate setDate:appDelegate.dateProductionDroneEndDate];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MM-dd-yyyy "];
NSString *strDate = [dateFormatter stringFromDate:self.endDate.date];
self.productionDroneEndDate.text = strDate;
}
self.txtProductionName.text = appDelegate.strProductionName;
self.txtProductionScene.text = appDelegate.strProductionScene;
self.txtProductionReel.text = appDelegate.strProductionReel;
self.txtProductionName.delegate = self;
self.txtProductionReel.delegate = self;
self.txtProductionScene.delegate = self;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:#selector(dismissKeyboard)];
[self.view addGestureRecognizer:tap];
}
SO far what I got from ur question and code, simple mistake is as below :-
- (void)viewDidLoad
{
[super viewDidLoad];
....
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MM-dd-yyyy "];
NSString *strDate = [dateFormatter stringFromDate:self.startDate.date];
AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
if(!appDelegate.dateProductionDroneStartDate) //As initially this will be true and current date will be set.
[self.startDate setDate:[NSDate date]];
//So as you set the current date in self.startDate but not in label.
//Added below line for setting your label
else
{
[self.startDate setDate:appDelegate.dateProductionDroneStartDate];
}
self.productionDroneStartDate.text = strDate;
......
}
This should get you working further.
Why can't you just set the label with todays date at start without even touching the Picker. Then when the picker is moved as you suggest the label will be updated as expected.
I want to give my user the option to "share" my apps detailed view page.
Once the user clicks "tweet this" I want the initialText to include a date string ('release_date') that's being parsed with JSON. I'm having trouble displaying the date string in a readable format.
This is how I'm formatting the date (in a NSObject)
- (NSString *) formattedDate {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSDate *readableDate = [dateFormatter dateFromString:self.release_date];
[dateFormatter setDateFormat:#"MMMM dd"];
return [dateFormatter stringFromDate:readableDate];
}
My release_date is a NSString (this is how the JSON looks)
release_date: "2013-11-16T00:00:00.000Z"
This is how I'm displaying the formattedDate in my detailedViewController
- (void)viewDidLoad
{
[super viewDidLoad];
if([_singleRelease objectForKey:#"release_date"] != NULL)
{
NSString *readableDate = [_singleRelease objectForKey:#"release_date"];
UpcomingRelease *singleRelease = [[UpcomingRelease alloc] init];
singleRelease.release_date = readableDate;
self.release_date.text = [NSString stringWithFormat:#"%#", singleRelease.formattedDate];
}
}
My SLComposeViewController
- (IBAction)shareOnTwitter:(id)sender {
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
{
SLComposeViewController *tweetSheet = [SLComposeViewController
composeViewControllerForServiceType:SLServiceTypeTwitter];
[tweetSheet setInitialText:[NSString stringWithFormat:#"%# is releasing on %#, via #soleresource", [_singleRelease objectForKey:#"release_name"], [_singleRelease objectForKey:#"release_date"]]];
[self presentViewController:tweetSheet animated:YES completion:nil];
}
}
Thanks
Your code is a bit disorganized. One option would be something like this:
- (NSString *) formattedDate:(NSString *)jsonDateString {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSDate *readableDate = [dateFormatter dateFromString:jsonDateString];
[dateFormatter setDateFormat:#"MMMM dd"];
return [dateFormatter stringFromDate:readableDate];
}
- (IBAction)shareOnTwitter:(id)sender {
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
{
SLComposeViewController *tweetSheet = [SLComposeViewController
composeViewControllerForServiceType:SLServiceTypeTwitter];
NSString *formattedDate = [self formattedDate:[_singleRelease objectForKey:#"release_date"]];
[tweetSheet setInitialText:[NSString stringWithFormat:#"%# is releasing on %#, via #soleresource", [_singleRelease objectForKey:#"release_name"], formattedDate]];
[self presentViewController:tweetSheet animated:YES completion:nil];
}
}