How To Get The Current Date From Device? - iphone

I am facing a weird problem with NSDate, when I try fetch a date from device, sometimes it shows previous month for some versions
Here is my chunk of code for reference
NSDate *date = [NSDate date];
NSDateFormatter *dateF = [[NSDateFormatter alloc]init];
[dateF setDateFormat:#" dd.MM.yyyy "];
NSString *selectedDate = [dateF stringFromDate:date];
Any inputs are appreciated, Thank you

To avoid later localizing problems you might use NSCalendar and its method components:fromDate:
Something like this:
NSCalendar * calendar = [NSCalendar currentCalendar];
NSDateComponents * components = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
fromDate:[NSDate date]];
NSString * stringDate = [NSString stringWithFormat:#"%d.%d.%d", components.day, components.month, components.year];

NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"hh:mma dd/MMM"];
NSString *dateString = [dateFormat stringFromDate:today];
NSLog(#"date: %#", dateString);
[dateFormat release];

This is an example by Apple so it looks like you have your upper-case / lower-case right
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd 'at' HH:mm"];
Are you sure your device's date is set right? Also have you tried setting the locale of the NSDateFormatter?
EDIT:
To address you question in comments: NSDate is a point in time irrespective of time zones, calendars and so so on. NSCalendar and NSDateFormatter allow you to convert this point in time into a representation that is correct in a given time zone, with a given calendar.

Related

NSDate wrong output when add day to NSDate

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
NSLog(#"%#",dateString);
// Retrieve NSDate instance from stringified date presentation
NSDate *dateFromString = [dateFormatter dateFromString:dateString];
// Create and initialize date component instance
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setDay:2];
// Retrieve date with increased days count
NSDate *newDate = [[NSCalendar currentCalendar]
dateByAddingComponents:dateComponents
toDate:dateFromString options:0];
NSLog(#"Original date: %#", [dateFormatter stringFromDate:dateFromString]);
NSLog(#"New date: %#", [dateFormatter stringFromDate:newDate]);
OutPut
2013-05-17
Original date: 2013-05-17
New date: 1412647-09-06
I add 2 day to that. The new date should be "2013-05-19?. Can anyone tell me what I wrong? Thank in advance.
I assume that you forgot to initialize the day variable. If you add
NSUInteger day = 2;
then your code produces the expected result in my test program.
The init methode of NSDateComponents does not initializes the components. Thus, e.g., year is undefined. Form Apple's documentation:
An instance of NSDateComponents is not responsible for answering questions about a date beyond the
information with which it was initialized. For example, if you initialize one with May 6, 2004,
its weekday is NSUndefinedDateComponent

Date Formatting style in IOS

I want to get date format in style "6Mar2012 7:03:34 AM". Can anyone tell me how shall I get exact that date formatting string.I want to get it in iOS 5.0 from a NSDate Object.
Use NSDateFormatter with the format string dMMMyyyy h:mm:ss a:
NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dMMMyyyy h:mm:ss a"];
NSString *dateString = [dateFormat stringFromDate:today];
[dateFormat release];

How to find days between dates stored in 2 strings

I have two strings both are in following date format (2011-03-22).
i have to compare them and find number of days between them.
Can anyone tell me how to do this..
Please also tell me the correct method to convert them back to NSDate.
Might be a couple of errors as i just typed this, but it speaks for itself and you should get the idea.
NSString *dateStringA = #"2011-03-22";
NSString *dateStringB = #"2011-03-27";
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
df.dateFormat = #"yyyy-MM-dd";
NSDate *dateA = [df dateFromString:dateStringA];
NSDate *dateB = [df dateFromString:dateStringB];
NSDateComponents *comps = [[NSCalendar currentCalendar] components:NSDayCalendarUnit fromDate:dateA toDate:dateB options:0];
int daysBetweenDates = comps.day; //This is your days between the 2 dates
NSDate *intervalDate = [[NSCalendar currentCalendar] dateFromComponents:comps]; //This date object represents the duration between them
 For string to date
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyy-MM-dd HH:mm:ss ZZZ"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:<NSString containing date>];
for date to string
NSString *date = [[NSDate date] description];

is there any easy way to get Date?

I'm new to iPhone development. I want to set default date to NSDate Object as string. I don't see any easy way or method...
I think there might be a method in NSCalender? If there's such a method, please tell me.
Thanks in advance.
I'm not totally clear on what you are asking, but to create an instance of an NSDate object with the current date, one calls:
NSDate * myDate = [NSDate date];
If you are saying that you have a c-string or NSString that needs to be parsed to initialize an NSDate object, that's another question.
I have some code posted here:
How get a datetime column in SQLite with Objective C
that shows how to create NSDates from NSStrings using NSDateFormatter.
If you want to create an NSDate from a string, you need to use an NSDateFormatter to do it. It's important to note that the formatter will use the current locale's time zone when constructing the date, unless you put a time-zone in as part of the format. For more information about constructing time zones, see NSTimeZone.
For example, to create a date using the ubiquitous format '2011-01-16 00:00' in UTC, you would do:
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm"];
// Only certain abbreviations are okay, like UTC. See docs for more info
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"]];
NSDate* midnight_26_jan_2011_utc = [formatter dateFromString:#"2011-01-26 00:00"];
// this will display in your system locale
// (for me, it shows 2011-01-25 19:00 +0500 because I'm America/New_York time)
NSLog(#"date: %#", midnight_26_jan_2011_utc);
[formatter release];
Edit: Added time to format string.
You will need to look at the NSDate and NSDateFormatter classes. Here's a simple example of how to use them:
NSString* defaultDateString = [NSString stringWithFormat:#"2011-01-22 15:30:00"];
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate* defaultDate = [dateFormatter dateFromString:defaultDateString];
[dateFormatter release];
and if you wanted to get the string from a date you can just use:
NSString* defaultDateString = [dateFormatter stringFromDate:defaultDate];
NSDateFormatter *DateFormatter=[[NSDateFormatter alloc] init];
[DateFormatter setTimeZone:[NSTimeZone defaultTimeZone]];
[DateFormatter setDateFormat:#"yyyy-MM-dd hh:mm:ss"]; //here,you can set the date format as you need
NSDate *now = [[[NSDate alloc] init]autorelease];
NSString *theDate = [DateFormatter stringFromDate:now];
Now, you can use the string the date. :)
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc]init]autorelease];
[dateFormatter setDateFormat:#"yyyy-mm-dd"];
NSDate *yourDate = [dateFormatter dateFromString:#"2011-01-26"];

Retrieving current local time on iPhone?

I'm looking to get the current hour and minute on a user's iPhone for display in an app that doesn't show the status bar. Is there a simple way to do this?
// get current date/time
NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// display in 12HR/24HR (i.e. 11:25PM or 23:25) format according to User Settings
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSString *currentTime = [dateFormatter stringFromDate:today];
[dateFormatter release];
NSLog(#"User's current time in their preference format:%#",currentTime);
-(void)currentTime
{
//Get current time
NSDate* now = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *dateComponents = [gregorian components:(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:now];
NSInteger hour = [dateComponents hour];
NSString *am_OR_pm=#"AM";
if (hour>12)
{
hour=hour%12;
am_OR_pm = #"PM";
}
NSInteger minute = [dateComponents minute];
NSInteger second = [dateComponents second];
[gregorian release];
NSLog(#"Current Time %#",[NSString stringWithFormat:#"%02ld:%02ld:%02ld %#", (long)hour, (long)minute, (long)second,am_OR_pm]);
}
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *currentTime = [dateFormatter stringFromDate:[NSDate date]]
[dateFormatter release]; dateFormatter = nil;
I think you should try this. The timeZone is important.
See this similar question for an answer. You will have to change it to your date format.
[[NSDate date] timeIntervalSince1970];
if you are looking to calculate time intervals, you are better off using CACurrentMediaTime
double currentTime = CACurrentMediaTime();
A shorter approach
NSDate * now = [NSDate date];
timeLabel.text = [NSDateFormatter localizedStringFromDate:now
dateStyle:NSDateFormatterNoStyle
timeStyle:NSDateFormatterShortStyle];
CFAbsoluteTimeGetCurrent()
Absolute time is measured in seconds relative to the absolute reference date of Jan 1 2001 00:00:00 GMT. A positive value represents a date after the reference date, a negative value represents a date before it. For example, the absolute time -32940326 is equivalent to December 16th, 1999 at 17:54:34. Repeated calls to this function do not guarantee monotonically increasing results. The system time may decrease due to synchronization with external time references or due to an explicit user change of the clock.