Xcode show current time using image - xcode

I make a simple clock in xcode.
For now i use a font to display hour and minutes, they are in two separate label.
How can i do for display image for time, if i don't want use a font but one image for every number?
For time i use this:
[oreLabel setFont:[UIFont fontWithName:#"Digital-7Mono" size:250]];
NSDate *today = [[NSDate alloc] init];
dateFormatter = [[NSDateFormatter alloc] init];
[self.dateFormatter setDateFormat:#"11"];
NSString *currentTime = [self.dateFormatter stringFromDate: today];
self.oreLabel.text = currentTime;
pollingTimer = [NSTimer scheduledTimerWithTimeInterval:kPollingInterval
target:self
selector:#selector(pollTime)
userInfo:nil
repeats:YES];
[today release];
Thanks for help

I think the NSDateComponents object might be helpful to you. Maybe something like this:
NSDate *today = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:(NSHourCalendarUnit
| NSMinuteCalendarUnit)
fromDate:today];
NSInteger hour = [components hour];
UIImage *hourImage = [UIImage imageNamed:
[NSString stringWithFormat:#"hour%d", hour]];

Related

Disable a particular date in UIDatePicker

I was trying to set up a uidatepicker for booking some events in the calendar.
I need to disable (hide) some particular dates in my UIDatePicker, for instance days when I'm out of town or on vacation.
Can you help me with this one?
Thanx a lot in advance.
Here is some code:
- (void)viewDidLoad
{
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:#"IT"];
[self.datePicker setLocale:locale];
NSString *min = #"20132015";
NSString *max = #"22132015";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"ddMMyyyy HH:mm"];
NSDate *datemin = [dateFormat dateFromString:min];
NSDate *datemax = [dateFormat dateFromString:max];
[self.view addSubview:datePicker];
datePicker.minuteInterval = 15;
datePicker.maximumDate = datemax;
datePicker.minimumDate = [NSDate date];
[datePicker addTarget:self action:#selector(disableDate) forControlEvents:UIControlEventValueChanged];
[datePicker addTarget:self
action:#selector(LabelChange:)
forControlEvents:UIControlEventValueChanged];
[super viewDidLoad];
// Do any additional setup after loading the view.
}
-(void)disableDate{
NSDate *pickedDate = datePicker.date; // Get current Date
NSDate *disabledDate = [?????;
if([pickedDate compare:disabledDate] == NSOrderedSame)
{
[datePicker setDate:disabledDate animated:YES];
}
}
-(void)getDisableDate
{
?????
}
- (void)LabelChange:(id)sender{
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"dd.MM.yyyy HH:mm"];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:#"IT"];
[self.datePicker setLocale:locale];
labelDate.text = [NSString stringWithFormat:#"%#",
[df stringFromDate:datePicker.date]];
NSLog(#"date:%#", datePicker.date);
}
UIDatePicker doesn't support ranges of dates. What I would do instead is to change the date whenever a bad date is selected, by using setDate:animated: to the nearest date that is selectable. Also, to show a message somewhere explaining why the selected date was changed.
Either that, or, write your own custom UIDatePicker using UIPickerView. Not too hard, I've done it before. The worst part is dealing with wrapping values (eg: 31 -> 1). Does involve more work, though.
Best solution is create custom UIDatePicker using UIPickerView it's too easy and in future you can do changes easily.
Check the link.

Date Time Display Issue

I have the following code:
NSString *dateString = #"01-02-2010 12:00:00 AM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy h:m:s a"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
[dateFormatter release];
When I set the above date in a DateTimePopup it shows "02/01/2010".
But when I use the same to add data to a GridView it shows
Full Date with Time and Zone.
I need to display only Date ie "02/01/2010"
kindly help
You need to set the date format for display:
NSString *dateString = #"01-02-2010 12:00:00 AM";
NSDateFormatter *inputDateFormatter = [NSDateFormatter new];
[inputDateFormatter setDateFormat:#"dd-MM-yyyy h:m:s a"];
NSDate *dateFromString = [inputDateFormatter dateFromString:dateString];
NSDateFormatter *displayDateFormatter = [NSDateFormatter new];
[displayDateFormatter setDateFormat:#"MM/dd/yyyy"];
NSString *displayDateString = [displayDateFormatter stringFromDate:dateFromString];
NSLog(#"displayDateString: %#", displayDateString);
NSLog output
displayDateString: 02/01/2010
Note: In the OP code the line
NSDate *dateFromString = [[NSDate alloc] init];
is unnecessary, on the very next line dateFromString is over written.

Using NSDate and NSDate components to calc time between 2 dates (Max 6 days, 23 hrs, 59 min, 59sec in the future)

UPDATE: This is the working example.
First we create a class to hold weekday, hr, min, and sec:
myClass.h
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
#interface myClass : NSObject {
NSString *weekday;
NSInteger hour;
NSInteger minute;
NSInteger second;
}
#property (nonatomic, strong) NSString *weekday;
#property (nonatomic, assign) NSInteger hour;
#property (nonatomic, assign) NSInteger minute;
#property (nonatomic, assign) NSInteger second;
#end
myClass.m
#import "myClass.h"
#implementation myClass
#synthesize weekday, hour, minute, second;
#end
Next, we need to create an instance of myClass that holds our date info.
Add this to ViewController.h:
#property (nonatomic, strong) NSMutableArray *myArray;
This code goes in ViewController.m wherever you'd like:
myArray = [[NSMutableArray alloc] init];
//Setup an instance of myClass
myClass *c = [[myClass alloc] init];
[c setWeekday:#"Monday"];
[c setHour:13];
[c setMinute:0];
[c setSecond:0];
[myArray addObject:c];
Next we need to figure out how far in the future our event is. Thanks to rdelmar we have the code to do this, his answer is below
//Create a func that returns an NSDate. It requires that the Weekday, HR, Min and Secs are passed into it.
-(NSDate *)getNextDateOn:(NSString *)weekday atHour:(NSInteger)hour minute:(NSInteger)mins second:(NSInteger)secs {
//Setup an array of weekdays to compare to the imported (NSString *)weekday
NSArray *array = [NSArray arrayWithObjects:#"Sunday",#"Monday",#"Tuesday",#"Wednesday",#"Thursday",#"Friday",#"Saturday",nil];
NSInteger weekdayNumber = [array indexOfObject:[weekday capitalizedString]] + 1;
//This code finds how many days in the future the imported (NSString *)weekday is
NSDate *now = [NSDate date];
NSCalendar *cal = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *nowComps = [cal components:NSWeekdayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:now];
NSInteger daysForward = (weekdayNumber - nowComps.weekday + 7) % 7;
//Lastly, create an NSDate called eventDate that consists of the
NSDateComponents *eventComps = [[NSDateComponents alloc] init];
[eventComps setDay:daysForward];
[eventComps setHour: hour - nowComps.hour];
[eventComps setMinute: mins - nowComps.minute];
[eventComps setSecond: secs - nowComps.second];
eventDate = [cal dateByAddingComponents:eventComps toDate:now options:0];
return eventDate;
}
Here, we take the newly created eventDate and use it to create our event in iCal:
EKEventStore *eventStore = [[EKEventStore alloc] init];
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.title = #"Move your car!";
event.startDate = eventDate;
event.endDate = [[NSDate alloc] initWithTimeInterval:60.0f * 60.0f sinceDate:event.startDate]; //1 hr long
[event addAlarm:[EKAlarm alarmWithRelativeOffset:60.0f * -30.0f]]; //30 min before
//eventLoc was created using CLGeocoder and the method reverseGeocodeLocation:
//The location is not necessary to create an event but if you'd like the code, ask and i'll post it.
[event setLocation:eventLoc];
[event setNotes:#"This event was set by me. ;P"];
[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err;
[eventStore saveEvent:event span:EKSpanThisEvent error:&err];
NSLog(#"Event Set");
I hope this helps someone as much as it's helped me.
:END OF UPDATE:
I've read through the documentation of NSDate hoping to find an easy way to find "the next upcoming Mon 1:00PM".
For instance, lets say the bakery is open 1 day a week (Thurs) from 9am - 6pm... If it is now Thurs, 8am, I want to get an NSDate for 1hr from now. If today were Thurs # 7pm, I'd want the NSDate for next Thurs at 9am.
I plan on making an event in iCal (tests have been successful) but the trouble is in calculating the event time.
Can you point me towards a good explanation of NSDate or help me figure out how to calculate the NSDate's I'm looking for?
I'm looking to fix this code:
EKEventStore *eventStore = [[EKEventStore alloc] init];
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.title = #"Bakery's Open!";
event.startDate = [[NSDate alloc] init];
event.endDate = [[NSDate alloc] initWithTimeInterval:600 sinceDate:event.startDate];
[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err;
[eventStore saveEvent:event span:EKSpanThisEvent error:&err];
To find a date like this requires using NSDateComponents and NSCalendar. The main task, I think, is to figure out how many days in the future your target date is. To do this you need to get the weekday date component of the current date and calculate how many days it is to the weekday you're looking for. I think the following code should get you close:
-(NSDate *)getNextDateOn:(NSString *)weekday atHour:(NSInteger)hour minute:(NSInteger)mins second:(NSInteger)secs {
NSArray *array = [NSArray arrayWithObjects:#"Sunday",#"Monday",#"Tuesday",#"Wednesday",#"Thursday",#"Friday",#"Saturday",nil];
NSInteger weekdayNumber = [array indexOfObject:[weekday capitalizedString]] + 1;
NSDate *now = [NSDate date];
NSCalendar *cal = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *nowComps = [cal components:NSWeekdayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:now];
NSInteger daysForward = (weekdayNumber - nowComps.weekday + 7) % 7;
NSDateComponents *eventComps = [[NSDateComponents alloc] init];
[eventComps setDay:daysForward];
[eventComps setHour: hour - nowComps.hour];
[eventComps setMinute: mins - nowComps.minute];
[eventComps setSecond: secs - nowComps.second];
NSDate *eventDate = [cal dateByAddingComponents:eventComps toDate:now options:0];
[eventComps release];
return eventDate;
}

Cocoa Date Picker formatting

This prints the selected datePicker's date to a textField like this:
February 9, 2012 ...
NSDate *theDate = [calendar dateValue];
if (theDate)
{
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
NSString *formattedDateString;
[formatter setDateStyle:NSDateFormatterLongStyle];
[formatter setTimeStyle:NSDateFormatterNoStyle];
formattedDateString = [formatter stringFromDate:theDate];
[dateString setStringValue: formattedDateString];
}
}
How do I format the printed string to look like this?
2012-02-09
I tried adding a dateFormatter to the textField and customizing how it should display a date. Doesn't work.
Thanks for the help.
You can do it like this:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd"];
NSDate *theDate = [calendar dateValue];
NSString *formatedDateString = [formatter stringFromDate:theDate];
[formatter release];

Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds

I basically need to get current date and time separately, formatted as:
2009-04-26
11:06:54
The code below, from another question on the same topic, generates
now: |2009-06-01 23:18:23 +0100|
dateString: |Jun 01, 2009 23:18|
parsed: |2009-06-01 23:18:00 +0100|
This is almost what I'm looking for, but I want to separate the day and time.
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:#"MMM dd, yyyy HH:mm"];
NSDate *now = [[NSDate alloc] init];
NSString *dateString = [format stringFromDate:now];
NSDateFormatter *inFormat = [[NSDateFormatter alloc] init];
[inFormat setDateFormat:#"MMM dd, yyyy"];
NSDate *parsed = [inFormat dateFromString:dateString];
NSLog(#"\n"
"now: |%#| \n"
"dateString: |%#| \n"
"parsed: |%#|", now, dateString, parsed);
this is what i used:
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd"];
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:#"HH:mm:ss"];
NSDate *now = [[NSDate alloc] init];
NSString *theDate = [dateFormat stringFromDate:now];
NSString *theTime = [timeFormat stringFromDate:now];
NSLog(#"\n"
"theDate: |%#| \n"
"theTime: |%#| \n"
, theDate, theTime);
[dateFormat release];
[timeFormat release];
[now release];
iPhone format strings are in Unicode format. Behind the link is a table explaining what all the letters above mean so you can build your own.
And of course don't forget to release your date formatters when you're done with them. The above code leaks format, now, and inFormat.
NSDateFormatter *dateformat = [[NSDateFormatter alloc] init];
[dateformat setDateFormat:#"Your Date Format"];
set the format to return is....
yyyy-MM-dd return 2015-12-17 date
yyyy-MMM-dd return 2015-Dec-17 date
yy-MM-dd return 15-12-17 date
dd-MM-yy return 17-12-15 date
dd-MM-yyyy return 17-12-2015 date
yyyy-MMM-dd HH:mm:ss return 2015-Dec-17 08:07:13 date and time
yyyy-MMM-dd HH:mm return 2015-Dec-17 08:07 date and time
For more Details Data and Time Format for Click Now.
Thank you.....
you can use this method just pass your date to it
-(NSString *)getDateFromString:(NSString *)string
{
NSString * dateString = [NSString stringWithFormat: #"%#",string];
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"your current date format"];
NSDate* myDate = [dateFormatter dateFromString:dateString];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"your desired format"];
NSString *stringFromDate = [formatter stringFromDate:myDate];
NSLog(#"%#", stringFromDate);
return stringFromDate;
}
nothing new but still want to share my method:
+(NSString*) getDateStringFromSrcFormat:(NSString *) srcFormat destFormat:(NSString *)
destFormat scrString:(NSString *) srcString
{
NSString *dateString = srcString;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//[dateFormatter setDateFormat:#"MM-dd-yyyy"];
[dateFormatter setDateFormat:srcFormat];
NSDate *date = [dateFormatter dateFromString:dateString];
// Convert date object into desired format
//[dateFormatter setDateFormat:#"yyyy-MM-dd"];
[dateFormatter setDateFormat:destFormat];
NSString *newDateString = [dateFormatter stringFromDate:date];
return newDateString;
}
For swift
var dateString:String = "2014-05-20";
var dateFmt = NSDateFormatter()
// the format you want
dateFmt.dateFormat = "yyyy-MM-dd"
var date1:NSDate = dateFmt.dateFromString(dateString)!;
Swift 3
extension Date {
func toString(template: String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = DateFormatter.dateFormat(fromTemplate: template, options: 0, locale: NSLocale.current)
return formatter.string(from: self)
}
}
Usage
let now = Date()
let nowStr0 = now.toString(template: "EEEEdMMM") // Tuesday, May 9
let nowStr1 = now.toString(template: "yyyy-MM-dd") // 2017-05-09
let nowStr2 = now.toString(template: "HH:mm:ss") // 17:47:09
Play with template to match your needs. Examples and doc here to help you build the template you need.
Note
You may want to cache your DateFormatter if you plan to use it in TableView for instance.
To give an idea, looping over 1000 dates took me 0.5 sec using the above toString(template: String) function, compared to 0.05 sec using myFormatter.string(from: Date).
NSDate *date = [NSDate date];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyy-MM-dd"]
NSString *dateString = [df stringFromDate:date];
[df setDateFormat:#"hh:mm:ss"];
NSString *hoursString = [df stringFromDate:date];
Thats it, you got it all you want.

Resources