Getting correct NSDate value - is this the most efficient method? - objective-c

I have this code to get the local date/time. It works but it seems a long way around the bush (10 statements) to get my current date/time value rather than the GMT time.
NSDate *currentDateGMT = [NSDate date];
NSDateFormatter *currentDateDateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *currentDateTimeZoneGMT = [NSTimeZone timeZoneWithName:#"GMT"];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
[currentDateDateFormatter setTimeZone: currentDateTimeZoneGMT];
[currentDateDateFormatter setDateFormat:#"yyyy-MM-dd HH:mm"];
[currentDateDateFormatter setLocale:locale];
NSString *currentDateString = [currentDateDateFormatter stringFromDate:currentDateGMT];
NSDate *currentDateAdjusted = [currentDateDateFormatter dateFromString:currentDateString];
[currentDateDateFormatter release];
Can someone confirm that this is the best way to obtain the current machine value?
Thanks

NSDateFormatter will default to the users time zone so the simplest solution is
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//lower case h for hour will also default to the users
//12/24 hour clock preference
[formatter setDateFormat:#"yyyy-MM-dd hh:mm"];
NSString *currentDate = [formatter stringFromDate:[NSDate date]];
[formatter release];

Related

Time from a TextView into NSDate

I'm building an iPhone app to take times: a car has to get at a given time at a point, so if the car is sooner or later, gets points.
I need to obtain the most precise timing as I can, so I want to use milliseconds, but as far results are disappointing.
The time is typed on a TextField, let's say 12:17:22 and the code is the following:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter setDateFormat:#"HH:mm:ss"];
timeLegStart = [NSDate new];
timeLegStart = [dateFormatter dateFromString:setStartTime.text];
NSLog(#"timeLegStart = %#",timeLegStart);
The output is 1970-01-01 11:17:22 +0000, and I'd like it to be 12:17:22:000
Set your NSDateFormatter's properties like this (replacing with your time zone info):
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:#"pt_BR"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"America/Sao_Paulo"]];
[dateFormatter setDateFormat:#"HH':'mm':'ss' 'z"];
[dateFormatter setLocale:locale];
The problem here is that NSDate comprises of date and time and they are not separately available. When you are giving the input date with time specs only it load the calendar start date values with the time you provided and creates a date. Hence here comes the date as output.
Actually there is no problem to work with that.
You can use the same formatter to get the time retrieved back:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter setDateFormat:#"HH:mm:ss"];
NSDate* timeLegStart = [NSDate new];
timeLegStart = [dateFormatter dateFromString:#"12:12:12"];
NSLog(#"timeLegStart = %#",[dateFormatter stringFromDate:timeLegStart]);
It will give you:
timeLegStart = 12:12:12
EDIT : when logging NSDate it will be in GMT format only.Since you set the timezone to local there date will be always displayed like what you got.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
[dateFormatter setDateFormat:#"HH:mm:ss"];
NSDate* timeLegStart = [NSDate new];
timeLegStart = [dateFormatter dateFromString:#"12:12:12"];
NSLog(#"timeLegStart = %#",timeLegStart);
Will give you:
2000-01-01 12:12:12 +0000
Well, I've sorted it out this way:
- (void)fijaTiempoInicio
{
//getting current day
NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:~ NSTimeZoneCalendarUnit fromDate:[NSDate date]];
[dateComponents setTimeZone:[NSTimeZone timeZoneWithName:#"Europe/Spain"]];
NSDate *currentDate = [[NSCalendar currentCalendar] dateFromComponents:dateComponents];
//extracting year, month and day from current date
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:#"dd"];
NSString *currentDayString = [NSString stringWithFormat:#"%#",[df stringFromDate:currentDate]];
[df setDateFormat:#"MM"];
NSString *currentMonthString = [NSString stringWithFormat:#"%#",[df stringFromDate:currentDate]];
[df setDateFormat:#"yyyy"];
NSString *currentYearString = [NSString stringWithFormat:#"%#", [df stringFromDate:currentDate]];
NSDateFormatter *ft = [[NSDateFormatter alloc]init];
[ft setTimeZone:[NSTimeZone localTimeZone]];
[ft setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSString *tempDate = [NSString stringWithFormat:#"%#-%#-%# %#",currentYearString,currentMonthString,currentDayString,txtTiempoInicioTramo.text];
NSLog(#"tempDate= %#",tempDate);
startTime = [ft dateFromString:tempDate];
NSLog(#"startTime= %#",startTime);
Then, anothe method calculate the difference between two NSDates, which is a figure in milliseconds -a float
- (IBAction)btnCapturarTiempo:(id)sender
{
NSDateFormatter *formatCarTime = [[NSDateFormatter alloc]init];
[formatCarTime setDateFormat:#"HH:mm:ss"];
[formatCarTime setTimeZone:[NSTimeZone timeZoneWithName:#"Europe/Madrid"]];
carTime = [NSDate date];
difference = [carTime timeIntervalSinceDate:startTime];
labelTiempoCoche.text = [NSString stringWithFormat:#"%f",difference];

How to get date and time of selected time zone from uipicker in Xcode

I'm trying to display date and time of selected time zone from uipicker in a label or text field I'm not getting any way to solve this problem, so please any one help me Thanks in advance.
SelectedTimeZone= [Weight objectAtIndex:[pickerView selectedRowInComponent:0]];
NSString *selectedzone = SelectedTimeZone;
NSCalendar *gregorian=[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setTimeZone:[NSTimeZone timeZoneWithName:selectedzone]];
NSDateComponents *timeZoneComps=[[NSDateComponents alloc] init];
NSDate *date=[gregorian dateFromComponents:timeZoneComps];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterFullStyle];
[formatter setDateFormat:#"dd-MM-yyyy HH:mm:ss "];
NSString *todaysDate= [formatter stringFromDate:[NSDate date]];
zone.text = todaysDate; I know this is not proper way but i'm new to xcode
[NSDate date]returns a date object representing the current date and time, no matter where you are. NSDates are not subject to places or time zones. There is just one NSDate that represents now or any other moment for that matter, not different date objects for every time timezone. Therefore, you should not attempt to convert a date between time zones.
NSDate *now = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterShortStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:#"Australia/Sydney"]];
NSLog(#"%#",[formatter stringFromDate:now]); //--> 9/9/11 11:54 PM
[formatter setTimeZone:[NSTimeZone timeZoneWithName:#"Europe/Paris"]];
NSLog(#"%#",[formatter stringFromDate:now]);
Or Refer same question here
To get date and time of selected time zone from uipicker provide date to formatter like this:
NSDate *now = [NSDate date];
NSCalendar *gregorian=[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setTimeZone:[NSTimeZone timeZoneWithName:selectedzone]];
NSDateComponents* timeZoneComps = [gregorian components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit|NSTimeZoneCalendarUnit fromDate:now];
NSDate *selectedDate=[gregorian dateFromComponents:timeZoneComps];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterFullStyle];
[formatter setDateFormat:#"dd-MM-yyyy HH:mm:ss "];
NSString *strSelectedDate= [formatter stringFromDate:selectedDate];
zone.text = strSelectedDate;

NSString to NSDate returns wrong date

I try to convert my NSString to NSDate object, but NSDateFormatter returns me a strange value.
Here is code:
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd HH:mm"];
NSDate *date = [dateFormat dateFromString:#"2012-08-15 00:00"];
[dateFormat release];
date value is 2012-08-14 21:00 +0000. It is 3 hours difference between NSString value and NSDate value. I think I've missed something, but I don't know what.
This is what i use:
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd HH:mm:ss ZZZ"];
NSDate *date = [dateFormat dateFromString:#"2012-08-15 00:00:00 +0000"];
NSLog(#"\n\n DATE: %# \n\n\n", date);
The +0000 is timezone, so make sure you use your timezone, like +0400.
Edit:
If you can't change the string, you can use this code to do it:
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd HH:mm"];
[dateFormat setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDate *date = [dateFormat dateFromString:#"2012-08-15 00:00"];
As i knew NSDate holds Grinwich time, so if you are in Moscow time zone, everything is wright
In objective c for NSDate if you did not set the setTimeZone, NSDate will take default timezone as localTimeZone. so if you need to get the exact date which you give as NSString string format, you need to setTimeZone as UTC. Follow the sample code, I guess it will be helpful for you.
NSDateFormatter *loacalformatter=[[NSDateFormatter alloc]init];
[loacalformatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *localDate =[loacalformatter dateFromString:#"2012-08-15 00:00"];
NSLog(#"localDate :%#",localDate);
NSDateFormatter *UTCformatter=[[NSDateFormatter alloc]init];
[UTCformatter setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
[UTCformatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *UTCDate =[UTCformatter dateFromString:#"2012-08-15 00:00"];
NSLog(#"UTCDate :%#",UTCDate);
UTCDate :2012-08-15 00:00 +0000 (GMT+00:00)
As suggested in the comments, if the date you receive is UTC then you need to convert it to your local timezone. Apple recommend you always use a properly configured NSDateFormatter when displaying dates, to handle localisation issues.
Here's some example code for turning an NSDate into an NSString:
NSDate *date = // initialised elsewhere
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
dateFormat.locale = [NSLocale currentLocale];
dateFormat.timeZone = [NSTimeZone localTimeZone];
dateFormat.timeStyle = NSDateFormatterShortStyle;
dateFormat.dateStyle = NSDateFormatterShortStyle;
dateFormat.locale = [NSLocale currentLocale];
NSString *dateAsString = [dateFormat stringFromDate:date];

NSDateFormatter in 12-hour mode

I have the following code.
NSDateFormatter *df = ...;
[df setTimeZone:[NSTimeZone defaultTimeZone]];
[df setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSSZZZ"];
NSDate * date = [df dateFromString:date_string]; //here is the problem
In 24-hour mode everything is ok. When 12-hour mode is set on device, stringFromDate returns null.
Format of date_string is the same all the time, date format too. Why does it happen?
In your NSDateFormatter "yyyy-MM-dd'T'HH:mm:ss.SSSZZZ" HH stands for 24 hour and hh stands for 12 hour
Try to set the locale in this way :
NSLocale *twelveHourLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
df.locale = twelveHourLocale;
To force instead to 24 hour, you can use :
NSLocale *twentyFour = [[NSLocale alloc] initWithLocaleIdentifier:#"en_GB"];
12-hour mode to 24 hour mode:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"hh:mm a"];
NSDate *amPmDate = [formatter dateFromString:amPmHourString];
[formatter setDateFormat:#"HH:mm"];
NSString *24HourString = [formatter stringFromDate:amPmDate]];
For 24-hour mode to 12 hour mode just do the opposite
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSLocale *locale = [[[NSLocale alloc]
initWithLocaleIdentifier:#"en_US_POSIX"] autorelease];
[dateFormat setLocale:locale];

Trouble printing NSDate returned from formatter

I want to see what is getting stored in an NSDate, so I am using NSLog, but it's showing (null), whereas if I print the string stf2, it's showing the proper value.
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"YYYY-MM-dd"];
NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MMM dd, yyyy"];
NSString *stf2 = [[pact.date componentsSeparatedByString:#" "] objectAtIndex:0];
NSLog(#"date %#",stf2);
NSDate *date_ = [formatter dateFromString:stf2];
pact.date = [formatter1 stringFromDate:date_];
NSLog(#"date %#",[NSDate date_]);
There are two specific problems in the code you've presented in the question.
Format Reset
First you do,
[formatter setDateFormat:#"YYYY-MM-dd"];
and then you initialize the second formatter followed by resetting the first formatter's format,
NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MMM dd, yyyy"];
To emphasize
[formatter setDateFormat:#"MMM dd, yyyy"];
This should've been formatter1 but is formatter.
Date Format
If you look at the format you've use YYYY-MM-dd, it looks fine. But apparent YYYY have a different purpose and can be different from our usual calendar year. You should use the lowercase y instead.
[formatter setDateFormat:#"yyyy-MM-dd"];
And I don't think you meant this but
NSLog(#"date %#",[NSDate date_]);
should be
NSLog(#"date %#", date_);
you need to correct the dateformatter by setting proper date formatter. first do this
[formatter setDateFormat:#"yyyy-dd-MM"];
//it should be in the way as your string is. like if your string is 2011-Jun- 27 then fromatter should be
[formatter setDateFormat:#"yyyy-MM-dd"];
set the formatter as per your string's date format. then get the date back from this line
NSDate *date_ = [formatter dateFromString:stf2];
Assuming "stf2" is your string, then perhaps your object formatter is nil.
Below functions will be helpful to you.
"getDateTimeFromString" will take date and time as argument and it will return NSDate object.\
-(NSDate *)getDateTimeFromString :(NSString *)tempDate :(NSString *)tempTime{
NSString *dateValue = [tempDate stringByAppendingFormat:#" %#",tempTime];
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm"];
NSDate *date = [[NSDate alloc] init];
date = [dateFormatter dateFromString:dateValue];
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:date];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:date];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:interval sinceDate:date] autorelease];
return date;
}
"getDateStringFromDate" will take NSDate as argument and it will return NSString.
So, you can NSLog that value.
-(NSString *)getDateStringFromDate :(NSDate *)dateValue{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd"];
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setTimeStyle:NSDateFormatterShortStyle];
[timeFormat setDateFormat:#"HH:mm a"];
NSString *theDate = [dateFormat stringFromDate:dateValue];
/*NSLog(#"\n"
"theDate: |%#| \n"
"theTime: |%#| \n"
, theDate, theTime);*/
return theDate;
}
Hope you will get the answer.