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
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.
Like if I am using the code.
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
[df setTimeZone:[NSTimeZone systemTimeZone]];
[df setDateFormat:#"dd.MM.yyyy"];
NSDate *today = [NSDate date];
NSString *log_date = [df stringFromDate:today];
//Generate Log Current Time.
[df setDateFormat:#"hh:mma"];
NSString *log_currenttime = [[df stringFromDate:today] lowercaseString];
NSLog(#"Log Date %#",log_date);
NSLog(#"Log Current Time %#",log_currenttime);
My log shows me :
Log Date 19.12.2011
Log Current Time 03:18pm
At least I can remove the Time Padding.
Change your format from hh:mma to h:mma
//Generate Log Current Time.
[df setDateFormat:#"h:mma"]; // Changed from hh:mma to h:mma
NSString *log_currenttime=[[df stringFromDate:today] lowercaseString];
NSLog(#"Log Current Time %#",log_currenttime);
This will output
Log Current Time 3:18pm
As Eric wrote, use h:mm will fail for example on czech calendar.
Only way to do that is use system formatter.
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
[df setTimeZone:[NSTimeZone systemTimeZone]];
[df setDateFormat:#"dd.MM.yyyy"];
[df setTimeStyle:NSDateFormatterNoStyle];
NSDate *today = [NSDate date];
NSString *log_date = [df stringFromDate:today];
//Generate Log Current Time.
[df setTimeStyle:NSDateFormatterShortStyle];
[df setDateStyle:NSDateFormatterNoStyle];
NSString *log_currenttime = [[df stringFromDate:today] lowercaseString];
NSLog(#"Log Date %#",log_date);
NSLog(#"Log Current Time %#",log_currenttime);
The problem with Aadhira's answer is that if the user then switches to metric the #h:mma formatting will override it and make 23:00 look like 11:00pm.
The padding comes from the users settings in Settings-->General-->International-->Region Format. For example if it is set to UK, you will get padding. If it is set to US you won't. You may want to respect this decision in your user interface.
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.
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];
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"];