iOS6 NSDateFormatter default year - nsdateformatter

Has anyone noticed that iOS6 NSDateFormatter defaults to year 2000 when no year is given while in
iOS6:
[[NSDateFormatter alloc] init] dateFromString: #"7:30am"]
=> 2000 Jan 1st, 7:30am
iOS5:
=> 1970 Jan 1st, 7:30am
Question:
1. Is there a better way to compare two different times? I have this subway app PATH Schedule/Map. The subway times are hardcoded in the database as numSecondsSince1970. I give people the next train arriving by comparing departure times with the current numSecondsSince1970.
Right now I am just appending the year 1970 to the time string "2:30am" => "1970 2:30am" but it seems like there is a better way
Thanks!

Yes I just noticed this issue. Apparently this bug is reported at Apple, see http://openradar.appspot.com/12358210
Edit: this is how I dealt with this issue in a project I'm working on...
// I use the following code in a category to parsing date strings
- (NSDate *)dateWithPath:(NSString *)path format:(NSString *)format
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
formatter.dateFormat = format;
NSString *string = [self valueWithPath:path];
return [formatter dateFromString:string];
}
// old parsing code that worked fine in iOS 5, but has issues in iOS 6
NSDate *date            = [element dateWithPath:#"datum_US" format:#"yyyy-MM-dd"];
NSDate *timeStart       = [element dateWithPath:#"aanvang" format:#"HH:mm:ss"];
NSTimeInterval interval = [timeStart timeIntervalSince1970];
match.timeStart         = [date dateByAddingTimeInterval:interval];
and the fix ...
// the following code works fine in both iOS 5 and iOS 6
NSDate *date = [element dateWithPath:#"datum_US" format:#"yyyy-MM-dd"];
NSDate *timeStart = [element dateWithPath:#"aanvang" format:#"HH:mm:ss"];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
calendar.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
NSUInteger units = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *timeComps = [calendar components:units fromDate:timeStart];
match.timeStart = [calendar dateByAddingComponents:timeComps toDate:date options:0];

Related

Different NSDate for same timestapm on ios versions (ios 6 and iOS7)

I ran into this weird issue where one of the method in my code is returning different dates for same timestamp value in different ios version.
Following is the code for that method.
+(NSDate *)getDateFromTheTimeStampAsDate:(NSInteger)timeStamp
{
NSLog(#"Timestamp - %d",timeStamp);
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
[dateFormatter setLocale:usLocale];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"PST"]];
[dateFormatter setDateFormat:#"MMM DD,yyyy"];
return [dateFormatter dateFromString:[dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:timeStamp]]];
}
For timestamp = 1361581013 following are the NSDates values returned from above function:
iOS6 - 2013/02/01
iOS7 - 2013/02/22
Is there anything wrong with this code ?
Update: I forgot to look at the date format, earlier. Thanks to one of the comment I managed to get correct date. This was a part of legacy code so in the decided to just trash it and use following:
[NSDate dateWithTimeIntervalSince1970:timeStamp];
First the output isn't ever close to the date. On the terminal try date -r 1361581013. At least then you can see if you are getting close.
Second, convert the timestamp to an NSDate. Log that see if its close.
NSDate *d = [NSDate dateWithTimeIntervalSince1970:1361581013] ;
NSLog(#"d = %#" , d) ;
Third after you know you are getting the NSDate then apply formats to it.
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterLongStyle;
df.timeStyle = NSDateFormatterLongStyle;
df.timeZone = [NSTimeZone timeZoneWithAbbreviation:#"PST" ];
NSLog(#"d with formatting 1 = %#" , [df stringFromDate:d]) ;
df.timeZone = [NSTimeZone timeZoneWithAbbreviation:#"EST" ];
NSLog(#"d with formatting 1 = %#" , [df stringFromDate:d]) ;
df.timeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT" ];
NSLog(#"d with formatting 1 = %#" , [df stringFromDate:d]) ;
Then you will know you got it right.
d = 2013-02-23 00:56:53 +0000
d with formatting 1 = February 22, 2013 at 4:56:53 PM PST
d with formatting 1 = February 22, 2013 at 7:56:53 PM EST
d with formatting 1 = February 23, 2013 at 12:56:53 AM GMT

NSString to NSDate conversion and NSDate don't give only date

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];
}

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

Why does time returned by [NSDate date] differ from my current time?

hi all
I am in India.And I have used the following code to get the current date.
[NSDate date]
it displaying the "2011-01-20 06:51:35 +0000" but actual time is "2011-01-20 12:21:35 +0000"
.Please tell me how to get the current date.
Thanks in advance
You need to use Date Formatter for this purpose.Below is the sample code for that.
NSDate *testDate=[NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM DD YY hh:mm"];//You can set your required format here
NSString *dt = [formatter stringFromDate:testDate];
[formatter release];
NSString *strDateTaken=dt;
Cheers
What does “actual time” mean? The current time in your time zone? Considering the time values given I’d guess that the first one is GMT and you want IST (+5:30). (See Time zones on Wikipeda.) Depends on what you want to do with the date – if you just want a formatted date and time in your current time zone, Aditya’s answer should work.
To Find Current date and difference between current date and Given date...its working code
NSDate *testDate=[NSDate date];
NSDateFormatter *formatterNew = [[NSDateFormatter alloc] init];
[formatterNew setDateFormat:#"dd-MM-yyyy HH:mm:ss "];
NSString *dt = [formatterNew stringFromDate:testDate];
NSString *strDateTaken=dt;
NSLog(#"Date=%#",strDateTaken);
[formatterNew release]; // This line can be removed if you are using ARC
NSDateFormatter *tempFormatter = [[[NSDateFormatter alloc]init]autorelease];
[tempFormatter setDateFormat:#"dd-MM-yyyy HH:mm:ss"];
NSDate *toDate = [tempFormatter dateFromString:strDateTaken];
NSLog(#"Current Date ==%#",toDate);
NSDateFormatter *tempFormatter1 = [[[NSDateFormatter alloc]init]autorelease];
[tempFormatter1 setDateFormat:#"dd-MM-yyyy HH:mm:ss"];
NSDate *startdate = [tempFormatter1 dateFromString:#"30-08-2011 16:25:00"];
NSLog(#"Last Date ==%#",startdate);
int i = [startdate timeIntervalSince1970];
int j = [toDate timeIntervalSince1970];
double X = j-i;
int days=(int)((double)X/(3600.0*24.00));
NSLog(#" Difference :%d",days);

Objective C - How can i get the weekday from NSDate?

I need to be able to get the weekday from nsdate, i have the following code and it always return 1. I tried to change the month, i tried everything from 1 to 12 but the result of the week day is always 1.
NSDate *date2 = [[NSDate alloc] initWithString:[NSString stringWithFormat:#"%d-%d-%d", 2010, 6, 1]];
unsigned units2 = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit;
NSCalendar *calendar2 = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components2 = [calendar2 components:units2 fromDate:date2];
int startWeekDay = [components2 weekday];
[date2 release];
[calendar2 release];
Creating an NSDateFormatter that only contains the weekday will do what you want.
NSDate *now = [NSDate date];
NSDateFormatter *weekday = [[[NSDateFormatter alloc] init] autorelease];
[weekday setDateFormat: #"EEEE"];
NSLog(#"The day of the week is: %#", [weekday stringFromDate:now]);
If you need internationalization, the NSDateFormatter can be sent a locale, which will give the proper translation.
The date formatters are controlled through this standard: Unicode Date Formats
Edit for Mac:
The format of the string has to be —YYYY-MM-DD HH:MM:SS ±HHMM according to the docs, all fields mandatory
Old answer (for iPhone and tested on simulator):
There is no (public) -initWithString: method in NSDate, and what you get returned is not what you expect.
Use a properly configured (you need to give the input format) NSDateFormatter and -dateFromString:.
I solved the problem, The problem was that the format of my date string was wrong:
NSDate *date = [[NSDate alloc] initWithString:[NSString stringWithFormat:#"%d-%d-%d 10:45:32 +0600", selectedYear, selectedMonth, selectedDay]];
and since i don't care about the time i randomly pass a time to the end of the string
I'm using Xcode 6.4
There are many ways to setup an NSDate. I won't go over that here. You've done it one way, using a string (A method I avoid due to it being very vulnerable to error), and I'm setting it another way. Regardless, access your components weekday or setDay methods.
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
[calendar setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en-US"]];
NSDateComponents *components = [calendar components:(NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitWeekday|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond) fromDate:[NSDate date]];
NSDate *date = [calendar dateFromComponents:components];
this way, you can get or set any of these components like this:
[components weekday] //to get, then doSomething
[components setDay:6]; //to set
and, of course, set NSDate *date = [calendar dateFromComponents:components];only after you've changed the components.
I added in the extra local and other components for context in case you'd like to set those too.
It's free code, don't knock it.
Anyone coming here looking for a more recent Swift 4 solution:
extension Date {
func getDayOfWeek() -> String {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.current
dateFormatter.locale = Locale(identifier: "en_US")
dateFormatter.setLocalizedDateFormatFromTemplate("EEEE")
return dateFormatter.string(from: self)
}
}
let inputString = "2018-04-16T15:47:39.000Z"
let result = inputString.getDayOfWeek()
result = Monday
Most upvoting answer in Swift 3.
let formatter = DateFormatter()
formatter.dateFormat = "EEEE"
print("The day of the week is \(formatter.string(from: Date()))")
I used the following website which helped with setting up the string to retrieve the format I wanted on my date
Coder Wall - Guide to objective c date formatting