NSString to NSDate conversion and NSDate don't give only date - objective-c

Hope you will doing good.
I have a date (November 14, 2012) in label, it means that
Label.text returns the string "November 14, 2012"
Now what I want is to convert this string into NSDate. I did it by using this code snippet.
formator.dateStyle=NSDateFormatterShortStyle;
formator.dateFormat=#"yyyy-MM-dd";
NSString *temp=[NSString stringWithFormat:#"%#",[formator stringFromDate:myDatePicker.date]];
NSLog(#"%#",temp);
NSDate *myDate=[formator dateFromString:temp];
NSLog(#"%#",myDate);
myDatePicker.dateoutput= November 14,2012
temp'soutput= 2012-11-14
myDate'soutput= 2012-06-13 19:00:00 +0000
myDate is also giving me time and GMT setting and also 1 day behind date i.e 13 instead of 14, which I really don't want to get. I just need only the date.
My requirement is to get the output of myDate 2012-11-14
Thanks for all of your help in anticipation.

Try this one and let me know :
NSDate *dateTemp = [[NSDate alloc] init];
NSDateFormatter *dateFormat1 = [[NSDateFormatter alloc] init];
NSDateFormatter *dateFormat2 = [[NSDateFormatter alloc] init];
[dateFormat1 setDateFormat:#"MM/dd/yy"];
[dateFormat2 setDateFormat:#"yyyy-MM-dd"];
dateTemp = [dateFormat1 dateFromString:newInvoice.date];
newDate.date = [dateFormat2 stringFromDate:dateTemp];
This will be helpfull :
-(NSDate *)dateWithOutTime:(NSDate *)datDate
if( datDate == nil ) {
datDate = [NSDate date];
}
NSDateComponents* comps = [[NSCalendar currentCalendar] components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:datDate];
return [[NSCalendar currentCalendar] dateFromComponents:comps];
}

Related

setFirstWeekday doesn't work

I have an issue: setFirstWeekDay doesn't work... I don't know why ...
NSCalendar *gregorianT = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[gregorianT setFirstWeekday:2];
NSDateFormatter *formatDayWeek = [[NSDateFormatter alloc] init];
[formatDayWeek setDateFormat:#"c EEEE"];
NSLog(#"date : %# value for date : %#", dateForMonth, [formatDayWeek stringFromDate:dateForMonth]);
This is what I got:
date : 2012-11-23 14:18:28 +0000 value for date : 6 Friday
And I should get date : 2012-11-23 14:18:28 +0000 value for date : 5 Friday
The issue is that you are really dealing with three separate objects here: an NSCalendar, an NSDate, and an NSDateFormatter (which is not using the NSCalendar object you created). The three aren't implicitly connected; when you pass in the NSDate to the date formatter, you're completely pulling your custom NSCalendar, with the modified weekday, out of the equation. Remember: an NSDate object is simply a measure of time from a reference point (such as number of seconds from 1/1/2001 Midnight GMT)... it's the calendar object that has the concept of "day name," day ordinality," etc for that measure of time.
If you want to see the modified ordinality, pass in your calendar object to the formatter:
NSCalendar *gregorianT = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[gregorianT setFirstWeekday:2];
NSDateFormatter *formatDayWeek = [[NSDateFormatter alloc] init];
[formatDayWeek setCalendar:gregorianT];
[formatDayWeek setDateFormat:#"c EEEE"];
NSLog(#"Value for date: %#", [formatDayWeek stringFromDate:dateForMonth]);
...or you can access the ordinality directly from your NSCalendar object.
NSCalendar *gregorianT = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[gregorianT setFirstWeekday:2];
NSUInteger valueOfDay = [gregorianT ordinalityOfUnit:NSWeekdayCalendarUnit inUnit:NSWeekCalendarUnit forDate:dateForMonth];
NSLog(#"Value for date : %ld", (long)valueOfDay);

Objective-C – NSDateFormatter dateFromString ignore time

If I'm not interested in the time can I ignore it? I.e I have a date string that looks like this #"2012-12-19T14:00:00" but I'm only interested in getting the date (2012-12-19) but if I set NSDateFormatter like [dateFormatter setDateFormat:#"yyyy-MM-dd"]; it will return me a nil NSDate.
An NSDate object will always contain a time component as well, as it is representing a point in time — from this perspective one could argue the name NSDate is misleading.
You should create a date formatter for creating dates from string, set the time to the start of the day and use a second date formatter to output the date without time component.
NSString *dateString = #"2012-12-19T14:00:00";
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss"];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateStyle:NSDateFormatterShortStyle];
[outputFormatter setTimeStyle:NSDateFormatterNoStyle];
NSDate *date = [inputFormatter dateFromString:dateString];
//this will set date's time components to 00:00
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit
startDate:&date
interval:NULL
forDate:date];
NSString *outputString = [outputFormatter stringFromDate:date];
NSLog(#"%#", outputString);
results in
19.12.12
while the format — as it is chosen by styling — will be dependent of your environment locale
all date string returns 10 characters for the date, what i mean is the date of todayy will be 2012-11-19
you can easily substring the date and use it as you want:
Example :
NSString* newDate = #"";
newDate = [[NSDate date]substringToIndex:10];
the out put will be : 2012-11-19

List of days in Objective C

I wonder how could I make a list of days from MONDAY to SUNDAY...
I did it so:
- (NSString *) stringWithDayNameOf:(int)day {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"D"];
NSDate *date = [dateFormat dateFromString:[NSString stringWithFormat:#"%i", day]];
[dateFormat setDateFormat:#"eeee"];
NSString* outer = [dateFormat stringFromDate:date];
outer = [outer uppercaseString];
return outer;
}
for (int i = 1; i <= 7; i++) {
NSLog(#"DAY: %#", [self stringWithDayNameOf:i]);
}
But it displays days from today... How to fix that or make simpler?
Thanks!!
Use NSDateFormatter's weekdaySymbols and friends (for short names etc.)
%D is the format specifier for "day of year", not "day of week". There's no specifier for numerical day of week, since (as far as I know) no-one writes dates that way.
You need to create your date using NSDateComponents and then format that:
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"eeee"];
NSCalendar * cal = [NSCalendar currentCalendar];
NSUInteger numWeekdays = [cal maximumRangeOfUnit:NSWeekdayCalendarUnit].length;
NSDateComponents * comp = [[NSDateComponents alloc] init];
for( NSUInteger day = 1; day <= numWeekdays; day++ ){
[comp setWeekday:day];
[comp setWeek:0];
NSDate * date = [cal dateFromComponents:comp];
NSString * dayName = [dateFormat stringFromDate:date];
NSLog(#"%#", dayName);
}
Also, NSDateFormatter knows the names of the days of the week already: -[NSDateFormatter weekdaySymbols]. The first day of the week in the Gregorian calendar is Sunday.

Get number of days between two NSDate dates in a particular timezone

I found the codes to calculate days difference between two dates here.
I write a method :
-(NSInteger)daysWithinEraFromDate:(NSDate *) startDate toDate:(NSDate *) endDate
{
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSInteger startDay=[gregorian ordinalityOfUnit:NSDayCalendarUnit
inUnit: NSEraCalendarUnit forDate:startDate];
NSInteger endDay=[gregorian ordinalityOfUnit:NSDayCalendarUnit
inUnit: NSEraCalendarUnit forDate:endDate];
return endDay-startDay;
}
This method has a problem: it can't consider the timezone thing. Even I add a line like this:
[gregorian setTimeZone:[NSTimeZone localTimeZone]];
My test code is like this:
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSString *strDate = #"2012-09-03 23:00:00";
NSDate *dateStart = [dateFormat dateFromString:strDate];
strDate = #"2012-09-04 01:00:00";
NSDate *dateEnd = [dateFormat dateFromString:strDate];
NSLog(#"Days difference between %# and %# is: %d days",[dateFormat stringFromDate:dateStart],[dateFormat stringFromDate:dateEnd],[self daysWithinEraFromDate:dateStart toDate:dateEnd]);
The result is:
Days difference between 2012-09-03 23:00:00 and 2012-09-04 01:00:00 is: 0 days
I want to get 1 day as result by the number of midnights between the two dates. My timezone is GMT +8. But this calculation is based on GMT, so I get the wrong days number. Is there anyway to solve this problem? Thank you.
Scott Lemmon's method can solve my problem. I rewrite my code like this:
-(NSInteger)daysWithinEraFromDate:(NSDate *) startDate toDate:(NSDate *) endDate
{
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setTimeZone:[NSTimeZone localTimeZone]];
NSDate *newDate1 = [startDate dateByAddingTimeInterval:[[NSTimeZone localTimeZone] secondsFromGMT]];
NSDate *newDate2 = [endDate dateByAddingTimeInterval:[[NSTimeZone localTimeZone] secondsFromGMT]];
NSInteger startDay=[gregorian ordinalityOfUnit:NSDayCalendarUnit
inUnit: NSEraCalendarUnit forDate:newDate1];
NSInteger endDay=[gregorian ordinalityOfUnit:NSDayCalendarUnit
inUnit: NSEraCalendarUnit forDate:newDate2];
return endDay-startDay;
}
If the time zone offset isn't working, how about just add or subtract it manually instead?
In your case NSDate *newDate = [oldDate dateByAddingTimeInterval:(-8 * 60 * 60)]; to subtract off your +8 hours.
Or if you want to find the GMT offset automatically as well then it would simply be NSDate *newDate = [oldDate dateByAddingTimeInterval:(-[[NSTimeZone localTimeZone] secondsFromGMT])
Another thought:
A perhaps easier solution would be to just disregard the time information altogether. Just set it to the same arbitrary number for both dates, then as long as the dates come from the same timezone you will always get the correct number of mid-nights between them, regardless of GMT offset.
What you really want is the NSDate method timeIntervalSinceDate:, and take that result and if it's more than 0 but less than 86400 (the number of seconds in a day), that's one day. Otherwise, divide your result by 86400 and you'll get the number of days.
The way you currently have your code, there's only 2 hours between the two days and that's why you are seeing a result of 0 and not one.
Edit - and to determine if midnight has happened, let's try this function I just wrote off the top of my head:
- (NSDate *) getMidnightDateFromDate: (NSDate *) originalDate
{
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSIntegerMax fromDate:originalDate];
[components setHour:0];
[components setMinute:0];
[components setSecond:0];
NSDate *midnight = [[NSCalendar currentCalendar] dateFromComponents:components];
return(midnight);
}
- (BOOL) howManyDaysDifferenceBetween: startDate and: endDate
{
NSDate * firstMidnight = [self getMidnightDateFromDate: startDate];
NSDate * secondMidnight = [self getMidnightDateFromDate: endDate];
NSTimeInterval timeBetween = [firstMidnight timeIntervalSinceDate: secondMidnight];
NSInteger numberOfDays = (timeBetween / 86400);
return(numberOfDays);
}
which I'm basing off Dave Delong's answer to this question. No guarantees that my code will work (I didn't test it), but I think the concept is sound.

Workout difference in months in Objective C

I would like to work out the difference in months
at the moment I have this code:
dateInterval = [endDate timeIntervalSinceDate:startDate];
But that returns a value in seconds, I would like to see the difference between the dates in months.
How would I do this?
Thanks
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateFormat:#"dd/MM/yyyy"];
NSDate *startDate = [inputFormatter dateFromString:#"07/03/2011"];
NSDate *endDate = [inputFormatter dateFromString:#"07/06/2011"];
NSInteger month_delta = [[[NSCalendar currentCalendar] components: NSMonthCalendarUnit fromDate: startDate toDate: endDate options: 0] month];
NSLog(#"---------------------------->>%d", month_delta);
[inputFormatter release]; // <-- in case not using ARC
it will log:
---------------------------->>3
You can create a NSDateComponents from the NSDates in question and just subtract the total months. (Total months = 12*year+currentMonth)
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDateComponents_Class/Reference/Reference.html#//apple_ref/occ/cl/NSDateComponents