iPhone Development - NSDate - help with my clock [duplicate] - iphone

Ii am trying to get date and time using date but when i run application it takes first time executed application time and date in short time is not changed.
NSDate *StrDate = [NSDate date];
NSDateFormatter *Dateformat = [[NSDateFormatter alloc]init];
[Dateformat setDateFormat:#"DD-MM-YYYY"];
NSMutableString *DateStr = [Dateformat stringFromDate:StrDate];
[UserCntrl.timeDisplay setText:DateStr];
[Dateformat setDateFormat:#"HH:MM"];
NSMutableString *timeStr=[Dateformat stringFromDate:StrDate];

Place a scheduled timer in your uiview did show (or did load) method:
[NSTimer scheduledTimerWithTimeInterval:1.0f // 1 second
target:self
selector:#selector(updateTime:)
userInfo:nil
repeats:YES];
Then, put this method in your View Controller:
- (void) updateTime:(id)sender
{
NSDate *StrDate = [NSDate date];
NSDateFormatter *Dateformat = [[NSDateFormatter alloc]init];
[Dateformat setDateFormat:#"DD-MM-YYYY HH:mm:SS"];
NSMutableString *DateStr = [Dateformat stringFromDate:StrDate];
[UserCntrl.timeDisplay setText:DateStr]; // or whatever code updates your timer. I didn't check this for bugs.
}
This will call the "updateTime:" method once a second, updating your controller.

[NSDate date] makes a date object of the time you call it. You must call it again to update the date. In other words, you must do StrDate = [NSDate date]; whenever you want to get the current date in your method.

You have a bug in your code:
Instead of
[Dateformat setDateFormat:#"HH:MM"];
it should be
[Dateformat setTimeFormat:#"HH:MM"];

Related

Save the current time when event is performed

In my app i am using zbar sdk to scan ticket and i want to save current time in sqlite when the camera takes the shot . How can i do this.
Thanks in advance.
Following code use for the getting the device local current time.
NSDate* sourceDate = [NSDate date];
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] autorelease];
May this Helping a lot for coding
You can write something like this:
NSDate *currentTime = [NSDate date];
Then you can extract appropriate values from NSDate object by using NSDateComponents or NSDateFormatter, if you need.
when you click save on ZBarReaderController , this bellow method called..
- (void) imagePickerController: (UIImagePickerController*) reader didFinishPickingMediaWithInfo: (NSDictionary*) info
{
NSDate *currentDateandTime = [NSDate date];
/// and save this date and time in your database
////with date formate see bellow my edited answer
/// this for get string from date with formate
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"EEE, dd-MM-yyyy hh:mm:ss a"];
NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
NSLog(dateString);
/// for get date from string with different formate use bellow code
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"EEE, d MMM yyyy HH:mm:ss z"];
NSDate *date = [dateFormatter dateFromString: dateString];
}
also for more detail about NSDate see my blog on bellow link..
http://parasjoshi3.blogspot.in/2012/01/convertstringtodatedatetostring.html
i hope this help you...
:)

Why NSDateFormatter returns NULL on 24h locals with a 12h time setup?

Hi Experts of the world,
I ran into a very weird problem:
I am formatting a string representing time from 00-23 (as returned by a Google service) in the following manner:
(passing in a string of lets say 14, should output either 14:00 or 2:00 PM, depends on user local)
+(NSString *) formatTime: (NSString *)timeToBeFormatted {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"HH"];
NSDate *date = [[NSDate alloc] init];
date = [dateFormat dateFromString:timeToBeFormatted];
// Convert date object to desired output format
[dateFormat setTimeStyle:NSDateFormatterShortStyle];
timeToBeFormatted = [dateFormat stringFromDate:date];
return timeToBeFormatted;
}
Everything works fine in all locals worldwide.
However, ONLY if a user has his TIME format set on 12h in a local where the default is 24h the formatter will return NULL ONLY for vales between 12-23.. Pretty weird i would say!
Example:
before formatter 12
after 12:00 AM
before formatter 13
after (null)
Any ideas why this could happen?
Thanks!
Solved! (inspired by the answers above)..
To solve the issue i am creating a specific Locale, then phrasing the stringToDate using this locale. Then i am creating another Locale with the default users preferences and phrasing the dateBackToString using that locale..
+(NSString *) formatTime: (NSString *)timeToBeFormatted
{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
//ADDED//
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
[dateFormat setLocale:enUSPOSIXLocale];
[dateFormat setDateFormat:#"HH"];
NSDate *date = [[NSDate alloc] init];
date = [dateFormat dateFromString:timeToBeFormatted];
//ADDED//
NSLocale *defualtLocale = [[NSLocale alloc] init];
[dateFormat setLocale:defualtLocale];
[dateFormat setTimeStyle:NSDateFormatterShortStyle];
timeToBeFormatted = [dateFormat stringFromDate:date];
return timeToBeFormatted;
}
I guess its quite costly for older devices but in the era of ARC and strong phones it works ;)
NSDateFormatter uses the current locale and time settings for parsing (and outputting) time. If you want to use a specific time format, set the locale for the date formatter yourself.
dateFormat.locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
Also, creating date formatter is expensive, if you call this function often you should cache the date formatter in a static variable.
I was also facing this issue before some time.
Use following code to formate your date as per your need.
+(NSDate *)getGMTDateToView:(NSDate *) availableDate formatter:(NSDateFormatter *)timeFormat {
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
[timeFormat setLocale:enUSPOSIXLocale];
NSTimeInterval timeZoneOffset = [[NSTimeZone defaultTimeZone] secondsFromGMT];
NSTimeInterval gmtTimeInterval = [availableDate timeIntervalSinceReferenceDate] + timeZoneOffset;
[timeFormat setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
[timeFormat setDateStyle:NSDateFormatterShortStyle];
[timeFormat setTimeStyle:NSDateFormatterShortStyle];
enUSPOSIXLocale = nil;
return [NSDate dateWithTimeIntervalSinceReferenceDate:gmtTimeInterval];
}
I found above code from one of apple's document (I have modified(little bit) it as per my need) but unable to find this link right now.

UIDatePicker return wrong NSDate

I am using UIDatePicker in my app and when i take the date that was chosen with:
NSDate *date = picker.date;
picker.date returned the day before the date that I chose.
any idea why it happens?
UIDatePicker will be displaying dates and times in your local timezone. However, NSDate does not have any concept of a timezone as it stores an absolute number of seconds since a reference date. When NSLogging a date, it shows the date and time in GMT. I expect if you work out your local timezone difference from GMT, you will see that it is the correct date.
Try creating an NSDateFormatter or NSCalendar with the appropriate locale and pass the date through that.
For further reading on this common topic, see this site written by another SO contributor.
give this a try worked for me
NSDate* sourceDate = [NSDate date];
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] autorelease];
//i'm outputting mine in a label you can use anything you like
NSString *dateOutput = [[[NSString alloc] initWithFormat:#"%#", destinationDate]autorelease];
self.dateLabel.text = dateOutput;
Remember to create the NSDate and then output it with a valid timezone and calendar!
NSDate only represents an absolute point in time. It has no concept of timezone (NY, Barcelona, ...) or calendar (Gregorian, Hebrew, ...).
UIDatePicker returns by default a NSDate with the system NSCalendar and NSTimeZone, but when you try to print it later, you do not format the output. You may have there the mismatch.
So 1st you need to setup the UIDatePicker correctly and 2nd transform the output with the NSDateFormatter so it knows the Calendar and the TimeZone being used.
An example code with the init of the UIDatePicker and then printing the result:
- (void)viewDidLoad
{
[super viewDidLoad];
// init the UIDatePicker with your values
// by default UIDatePicker inits with today, system calendar and timezone
// Only for teaching purposes I will init with default values
NSDate * now = [[NSDate alloc] init];
[_datePicker setDate: now]
animated: YES];
_datePicker.timeZone = [NSTimeZone localTimeZone];
_datePicker.calendar = [NSCalendar currentCalendar];
[_datePicker addTarget: self
action: #selector(getDatePickerSelection:)
forControlEvents:UIControlEventValueChanged];
}
-(void)getDatePickerSelection:(id) sender
{
// NSDateFormatter automatically inits with system calendar and timezone
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// Setup an output style
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
// Medium style date, short style time => "Nov 23, 1937 3:30pm"
NSString *dateString = [dateFormatter stringFromDate:date];
}
Check the answer I did for another very similar question:
NSDate output using NSDateFormatter
Did you check the timezone?
When you print an NSDate it will use GMT as it timezone.
If you set the system timezone to the NSDateFormatter you might get an other date, because it will take the timezone and calculate the time accordingly.
Add this code and see if the output is correct:
NSDate *date = picker.date;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeZone:NSDateFormatterNoStyle];
[dateFormatter setLocale:[NSLocale currentLocale]];
NSLog(#"Date: %#", [dateFormmater stringFromDate:date]);
[dateFormatter release], dateFormatter = nil;
Just add one line of code
self.datePicker.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
0 is for GMT 00 . Add according to your time zone.

How to set the Dateformat for current date in iphone application?

I am developing one application. In that i write the below code for setting the DateFormat for current date. But it is working upto 9th month only. From 10th month onwards it gives the nil value. So please tell me how to solve this one. My code is as below:
NSDate *datestr = clInfo.cldrinfodate;
NSDateFormatter *dateFormat1 = [[NSDateFormatter alloc] init];
[dateFormat1 setDateFormat:#"MM/dd/yyyy hh:mma"];
NSString *date1 = [dateFormat1 stringFromDate:datestr];
you can try this one.
NSDate * mCurrentDate = [NSDate date];
NSLog(#"current date=%#",mCurrentDate);
NSDateFormatter *dt=[[NSDateFormatter alloc] init];
[dt setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSString *st=[dt stringFromDate:mCurrentDate];

Putting current time into label

Ii am trying to get date and time using date but when i run application it takes first time executed application time and date in short time is not changed.
NSDate *StrDate = [NSDate date];
NSDateFormatter *Dateformat = [[NSDateFormatter alloc]init];
[Dateformat setDateFormat:#"DD-MM-YYYY"];
NSMutableString *DateStr = [Dateformat stringFromDate:StrDate];
[UserCntrl.timeDisplay setText:DateStr];
[Dateformat setDateFormat:#"HH:MM"];
NSMutableString *timeStr=[Dateformat stringFromDate:StrDate];
Place a scheduled timer in your uiview did show (or did load) method:
[NSTimer scheduledTimerWithTimeInterval:1.0f // 1 second
target:self
selector:#selector(updateTime:)
userInfo:nil
repeats:YES];
Then, put this method in your View Controller:
- (void) updateTime:(id)sender
{
NSDate *StrDate = [NSDate date];
NSDateFormatter *Dateformat = [[NSDateFormatter alloc]init];
[Dateformat setDateFormat:#"DD-MM-YYYY HH:mm:SS"];
NSMutableString *DateStr = [Dateformat stringFromDate:StrDate];
[UserCntrl.timeDisplay setText:DateStr]; // or whatever code updates your timer. I didn't check this for bugs.
}
This will call the "updateTime:" method once a second, updating your controller.
[NSDate date] makes a date object of the time you call it. You must call it again to update the date. In other words, you must do StrDate = [NSDate date]; whenever you want to get the current date in your method.
You have a bug in your code:
Instead of
[Dateformat setDateFormat:#"HH:MM"];
it should be
[Dateformat setTimeFormat:#"HH:MM"];