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
Related
I am working on a project where i need to set an alarm on 7 days before particular date the user has selected from date picker.
I used the following code to get the date from user
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateStyle:NSDateFormatterFullStyle];
NSString *dateStr = [NSString stringWithFormat:#"%#",[df stringFromDate:datePickerObj.date]];
[df release];
Can any one please tell me how to get the date of 7 days previous to the selected date.
Thanks in advance
Use dateByAddingComponents:toDate:options:, like this:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.day = -7;
NSDate *earlierDate = [calendar dateByAddingComponents:components
toDate:datePickerObj.date options:0];
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.
I have a time: 7:46 am
I want to convert this to NSDate. I do this:
NSDateFormatter *f = [NSDateFormatter new];
[f setDateFormat:#"h:mm a"];
NSDate *sr = [f dateFromString:#"7:46 am"];
I NSLog sr and I get 1969-12-31 22:46:00 +0000
Those times are not the same. Why is this so messed up?
No. Its not strange. NSDateConverter & NSDate are just doing their intended job here.
You are trying to convert "7:46 am" into a date. It contains only the time. No date is specified in the string. NSDate will default to "1970-01-01"(Unix epoch) if no date is specified. So after you convert the string you will get the date "1970-01-01 7:46 am". When you trying to display this in NSLog, if will display the date after adjusting the timeZone offset value. I guess you live in Japan or Korea. Probably the offset of your region is +09:00. So it diaplays the date subtracting the offset. So you are seeing "1969-12-31 22:46:00 +0000" in the log.
You can use the following method to set that time to a particular date, may be today.
NSString *timeStr = #"7:46 am";
NSDateFormatter *f = [NSDateFormatter new];
[f setDateFormat:#"yyyy-MM-dd"];
NSString *dateStr = [f stringFromDate:[NSDate date]]; // dateStr = 2011-06-10
dateStr = [dateStr stringByAppendingFormat:#" %#", timeStr]; // dateStr = 2011-06-10 7:46 am
[f setDateFormat:#"yyyy-MM-dd h:mm a"];
NSDate *sr = [f dateFromString:dateStr];
You aren't providing the day or the timezone... assuming you want to express "today at 7:42am", you can use this code:
NSDate *currentDate = [NSDate date];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setHour:7];
[comps setMinute:42];
NSDate *myDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];
[comps release];
The NSLog of myDate should give you the expected output now (assuming you wanted today#7:46am).
Since you are only specifying the time that you want the NSDate to refer to, and not the date, the formatter is using the default date (which seems to be very close to the UNIX epoch). Like Julio said, you should specify the current date as well, if you want the NSDate to refer to the time on that specific date.
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];
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.