Building NSDate from integers (year ... second) with Cocoa/objective-C - objective-c

I have year, mont, ... , second in integer type, and I need to build NSDate from them.
I tried this code, but I got (null).
NSDateFormatter *tempFormatter = [[[NSDateFormatter alloc]init]autorelease];
[tempFormatter setDateFormat:#"yyyy-mm-dd hh:mm:ss"];
NSString* message = [NSString stringWithFormat:#"%04d-%02d-%02d %02d:%02d:%02d", year, month, day, hour, minute, second];
NSDate *day3 = [tempFormatter dateFromString:message];
What's wrong with this code?

It would be more straightforward to create an NSDateComponents with your date components, and then use NSCalendar's dateFromComponents: to convert it to a date. The documentation for NSDateComponents has an example of how to do exactly this:
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:day];
[comps setMonth:month];
[comps setYear:year];
[comps setHour:hour];
[comps setMinute:minute];
[comps setSecond:second];
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [cal dateFromComponents:comps];
[comps release];

instead of
[tempFormatter setDateFormat:#"yyyy-mm-dd hh:mm:ss"];
write
[tempFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];

Related

how to convert localized Date String to NSDate

I have NSString *localized_Date = minutesSinceMidnightToLocalizedTime (time units)
I get this string as 4:30 am, 10.00pm
how do I convert this string to NSDate?
PLease let me know.
I know it's a bit long code, but I wanted to make it as readable as possible.
This code uses minutesSinceMidnight instead of the localized string.
NSDate *currentDate = [NSDate date];
NSDateComponents *currentDateComponents = [calendar components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:currentDate];
NSDateComponents *currentDateToMidnight = [[NSDateComponents alloc] init];
[currentDateToMidnight setHour:-[currentDateComponents hour]];
[currentDateToMidnight setMinute:-[currentDateComponents minute]];
[currentDateToMidnight setSecond:-[currentDateComponents second]];
NSDate *midnight = [calendar dateByAddingComponents:currentDateToMidnight toDate:currentDate options:0];
NSDateComponents *midnightToDesiredDate = [[NSDateComponents alloc] init];
[midnightToDesiredDate setMinute:minutesSinceMidnight];
NSDate *desiredDate = [calendar dateByAddingComponents:midnightToDesiredDate toDate:midnight options:0];
NSDateFormatter is your friend, use the formats that suits your date/time
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
[df setDateFormat:[NSString stringWithFormat:#"dd MMM yyyy HH:mm"]];
NSDate *_date = [df dateFromString:string];
Johan
Try this code:
NSString *dateString = #"4:30 am";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"hh:mm a"];
NSDate *date = [dateFormatter dateFromString:dateString];
Hope this will help you.

Objective C: Incorrect Output while using NSDates

I am trying to get the start and end dates of the current month. There are a few similar questions here, but I am getting unexpected results while using them. Here's what I did:
NSDate *monthStart,*monthEnd;
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [cal components:NSDayCalendarUnit fromDate:[NSDate date]];
[comps setDay:1];
[comps setHour:0];
[comps setMinute:0];
[comps setSecond:0];
monthStart = [cal dateFromComponents:comps];
[comps setDay:[[NSCalendar currentCalendar]
rangeOfUnit:NSDayCalendarUnit
inUnit:NSMonthCalendarUnit
forDate:[NSDate date]].length];
[comps setHour:23];
[comps setMinute:59];
[comps setSecond:59];
monthEnd = [cal dateFromComponents:comps];
NSLog(#"%#",monthStart);
NSLog(#"%#",monthEnd);
Unfortunately the output is :
2012-12-24 15:39:28.159 Popup[1010:403] 0001-12-31 18:06:32 +0000
2012-12-24 15:39:28.160 Popup[1010:403] 0001-01-31 18:06:31 +0000
BTW, the timezone configured in my machine is +5:30
I have modified your code little, to get the correct answer
NSDate *monthStart,*monthEnd;
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *currentDate = [NSDate date];
NSDateComponents *comps = [cal components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:currentDate];
[comps setDay:1];
[comps setHour:0];
[comps setMinute:0];
[comps setSecond:0];
[cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:19800]];
monthStart = [cal dateFromComponents:comps];
[comps setDay:[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:[NSDate date]].length];
[comps setHour:23];
[comps setMinute:59];
[comps setSecond:59];
monthEnd = [cal dateFromComponents:comps];
NSLog(#"Start %#",monthStart);
NSLog(#"End %#",monthEnd);
If you want to know the starting and ending date for current month...
Starting is always 1st, and ending can be calculated by month name!!!
Then it is very simple date arithmetic,
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSMutableArray *months=[NSMutableArray arrayWithObjects:#"Jan",#"Feb",#"Mar",#"Apr",#"May",#"Jun",#"Jul",#"Aug",#"Sep",#"Oct",#"Nov",#"Dec", nil];
NSMutableArray *days=[NSMutableArray arrayWithObjects:#"31",#"28",#"31",#"30",#"31",#"30",#"31",#"31",#"30",#"31",#"30",#"31", nil];
//check if leap
[dateFormat setDateFormat:#"YYYY"];
NSInteger year=[[dateFormat stringFromDate:[NSDate date]]integerValue];
if(((year%4==0)&&(year%100!=0))||(year%400==0)) {
[days replaceObjectAtIndex:1 withObject:#"29"];
}
NSMutableDictionary *daysInMonthDict=[[NSMutableDictionary alloc]initWithObjects:days forKeys:months];
[dateFormat setDateFormat:#"MMM"];
NSLog(#"Starting date is 1 and ending date is %#",[daysInMonthDict objectForKey:[dateFormat stringFromDate:[NSDate date]]]);

NSCalendar and NSDateComponents returning unexpected date

I'm trying to create an NSDate from NSCalendar and NSDateComponents with:
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone localTimeZone]];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:[self.day intValue]];
[components setMonth:[self.month intValue]];
[components setYear:[self.year intValue]];
self.date = [calendar dateFromComponents:components];
When the day, month, year are : 9/31/2011 the NSDate is for 10/1/2011. I set the timezone for the NSCalendar after testing which didn't change the NSDate. I also tried
[calendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"GMT"]];
Which gave me back 9/30/2011. Anyone see an error in the way I'm calculating this?
Thanks.
Well, september 31 is really october first.
But a component has to know in which calendar to work. The following code is from apple
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:6];
[comps setMonth:5];
[comps setYear:2004];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [gregorian dateFromComponents:comps];
[comps release];

How to get today's date in the Gregorian format when phone calendar is non-Gregorian?

NSDate *now = [[NSDate alloc] init];
gives the current date.
However if the phone calendar is not Gregorian (on the emulator there is also Japanese and Buddhist), the current date will not be Gregorian.
The question now is how to convert to a Gregorian date or make sure it will be in the Gregorian format from the beginning. This is crucial for some server communication.
Thank you!
NSDate just represents a point in time and has no format in itself.
To format an NSDate to e.g. a string, you should use NSDateFormatter. It has a calendar property, and if you set this property to an instance of a Gregorian calendar, the outputted format will match a Gregorian style.
NSDate *now = [NSDate date];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setCalendar:gregorianCalendar];
[formatter setDateStyle:NSDateFormatterFullStyle];
[formatter setTimeStyle:NSDateFormatterFullStyle];
NSString *formattedDate = [formatter stringFromDate:now];
NSLog(#"%#", formattedDate);
[gregorianCalendar release];
[formatter release];
The picked answer actually I can't compare them. only display is not enough for my project.
I finally come up with a solution that covert (NSDate) currentDate -> gregorianDate
then we can compare those NSDates.
Just remember that the NSDates should be used temporary .(it do not attach with any calendar)
NSDate* currentDate = [NSDate date];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *gregorianComponents = [gregorianCalendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:currentDate];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:[gregorianComponents day]];
[comps setMonth:[gregorianComponents month]];
[comps setYear:[gregorianComponents year]];
[comps setHour:[gregorianComponents hour]];
[comps setMinute:[gregorianComponents minute]];
[comps setSecond:[gregorianComponents second]];
NSCalendar *currentCalendar = [NSCalendar autoupdatingCurrentCalendar];
NSDate *today = [currentCalendar dateFromComponents:comps];

get NSDate from the day of the year

I have a the day of the year for example 346.
I want to get NSDate to now what month and day it means.
Your steps here:
Instantiate calendar
Build a date with 1st Jan. of the year
Add the number of days - 1 and build a date with that
Get the components you are interested in
Watch out if the date you get is 0- or 1-based.
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:theYear];
[comps setMonth:1];
[comps setDay:1];
NSDate *date = [gregorian dateFromComponents:comps];
[comps release];
NSDateComponents *compsToAdd = [[NSDateComponents alloc] init];
[comps setDay:theDay-1];
NSDate *finalDate = [gregorian dateByAddingComponents:compsToAdd date options:0];
[compsToAdd release]
NSDateComponents *interestingComponents = [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit) fromDate:finalDate];
NSInteger day = [interestingComponents day];
NSInteger month = [interestingComponents month];
[gregorian release];
See the -dateByAddingComponents:toDate:options: method of NSCalendar.