Converting a value into NSDate - iphone

I have this ticks value "634758517020305000" which corresponds to 21st June 2012. I tried to convert the tick value into NSDate object like this:
NSString *str = #"634758517020305000";
NSInteger offset = [[NSTimeZone defaultTimeZone] secondsFromGMT];
NSDate *date = [[NSDate dateWithTimeIntervalSince1970:
[[str substringWithRange:NSMakeRange(0, [str length])] intValue]]
dateByAddingTimeInterval:offset];
static NSDateFormatter *dateFormatter = nil;
if (dateFormatter == nil) {
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
NSString *fourDigitYearFormat = [[dateFormatter dateFormat] stringByReplacingOccurrencesOfString:#"yy" withString:#"yyyy"];
[dateFormatter setDateFormat:fourDigitYearFormat];
}
// There you have it:
NSString *outputString = [dateFormatter stringFromDate:date];
But I got the output: 1/19/2038. If anyone knows where I am doing wrong, please let me know.

your Unix timestamps is wrong. it should be 1340236800
check your Unix timestamps Here

Related

ios: String to Date conversion

I am trying to convert my date from NSString to NSDate using following code
NSDateFormatter *dateformatter = [[NSDateFormatter alloc]init];
[dateformatter setDateStyle:NSDateFormatterShortStyle];
[dateformatter setTimeStyle:NSDateFormatterNoStyle];
[dateformatter setDateFormat:#"dd/MM/yyyy"];
NSDate *myDate = [[NSDate alloc] init];
currMonth = 3;
currYear = 2012;
NSString *str = [NSString stringWithFormat:#"01/%2d/%d", currMonth, currYear];
str = [str stringByReplacingOccurrencesOfString:#" " withString:#"0"];
myDate = [dateformatter dateFromString:str];
NSLog(#"myStr: %#",str);
NSLog(#"myMonth: %2d",currMonth);
NSLog(#"myYear: %d",currYear);
NSLog(#"myDate: %#",myDate);
Above code is giving me wrong date. Can anyone please help?
What is your output? Keep in mind, that NSDate is in UTC.
2012-03-01 00:00:00 (GMT+1) is 2012-02-39 23:00:00 (UTC)
Another tip:
%02 formats your integers with leading zeros.
Try this:
-(NSDate *)dateFromString:(NSString *)string
{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
[dateFormat setLocale:locale];
[dateFormat setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSTimeInterval interval = 5 * 60 * 60;
NSDate *date1 = [dateFormat dateFromString:string];
date1 = [date1 dateByAddingTimeInterval:interval];
if(!date1) date1= [NSDate date];
[dateFormat release];
[locale release];
return date1;
}
Tell me if it helps u :]
try
NSDateFormatter *dateformatter = [[NSDateFormatter alloc]init];
[dateformatter setDateStyle:NSDateFormatterShortStyle];
[dateformatter setTimeStyle:NSDateFormatterNoStyle];
[dateformatter setDateFormat:#"dd/MM/yyyy"];
NSDate *myDate = [[NSDate alloc] init];
int currMonth = 3;
int currYear = 2012;
NSString *str = [NSString stringWithFormat:#"01/%2d/%d", currMonth, currYear];
str = [str stringByReplacingOccurrencesOfString:#" " withString:#"0"];
//SET YOUT TIMEZONE HERE
dateformatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:#"PDT"];
myDate = [dateformatter dateFromString:str];
NSLog(#"myStr: %#",str);
NSLog(#"myMonth: %2d",currMonth);
NSLog(#"myYear: %d",currYear);
NSLog(#"myDate: %#",myDate);

Problem in getting time

HI i need to increment 15 minutes in time intrval which i get in the webservice .
The code is as follows
NSString *dateString =obj.String_date_start; // start time is 2011-07-01
dateString = [dateString stringByAppendingString:[NSString stringWithFormat:#" %# +0000",obj.String_time_start]]; //After this statement the date is 2011-07-01 03:00:00 +0000
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss Z"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
NSDate *scheduledForYellow = [dateFromString dateByAddingTimeInterval:900];
[dateFormatter release];
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateFormat:#"yyyy-MM-dd HH:mm:ss Z"];
NSString *strTime = [dateFormatter1 stringFromDate:scheduledForYellow];
[dateFormatter1 release];
NSArray *aryy = [strTime componentsSeparatedByString:#" "];
NSLog(#"end time ======>>>%#",[aryy objectAtIndex:1]);
obj.String_StaticEndTime = [aryy objectAtIndex:1];
Here to add 15 minutes to my start time i have written the above code , but in end time that is [aryy objectAtIndex:1] does not give me the correct time.What i wanted to do is increment 15 minutes for whatever date i get in start date .Dont know whats the issue is.
`
It must be because of the default timezone (local timezone) that the date formatter uses to generate the string. I have modified your code a bit to reuse the date formatter and fixed a leak with dateFromString.
NSString *dateString = obj.String_date_start; // start time is 2011-07-01
dateString = [dateString stringByAppendingString:[NSString stringWithFormat:#" %# +0000",obj.String_time_start]]; //After this statement the date is 2011-07-01 03:00:00 +0000
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss Z"];
NSDate * dateFromString = [dateFormatter dateFromString:dateString];
NSDate * scheduledForYellow = [dateFromString dateByAddingTimeInterval:900];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"GMT"]];
NSString * strTime = [dateFormatter dateFromString:scheduledForYellow];
NSArray * aryy = [strTime componentsSeparatedByString:#" "];
NSLog(#"end time ======>>>%#",[aryy objectAtIndex:1]);
obj.String_StaticEndTime = [aryy objectAtIndex:1];
This should fix the issue. Let me know if you face any issues.

From string with locale to date on iphone sdk

I trying to find a way to convert a string into a date with a given locale identifier.
I have for example an italian date (locale: it_IT) I want to convert into a valid date object.
NSDate *GLDateWithString(NSString *string, NSString *localeIdentifier) {
[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:localeIdentifier];
[formatter setLocale:locale];
[locale release];
NSDate *date = [formatter dateFromString:string];
[formatter release];
return date;
}
this code does not work, the date is nil.
I can't figure out how I should use the locale setting for my purpose.
The solution is to use getObjectValue:forString:range:error: method of NSDateFormatter and set the correct date and time style ad follow:
- (NSDate *)dateWithString:(NSString *)string locale:(NSString *)localeIdentifier {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeStyle:NSDateFormatterNoStyle];
[formatter setDateStyle:NSDateFormatterShortStyle];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:localeIdentifier];
[formatter setLocale:locale];
[locale release];
NSDate *date = nil;
NSRange range = NSMakeRange(0, [string length]);
NSError *error = nil;
BOOL converted = NO;
converted = [formatter getObjectValue:&date forString:string range:&range error:&error];
[formatter release];
return converted? date : nil;
}
example:
NSString *italianDate = #"30/10/2010";
NSString *italianLocale = #"it_IT";
NSDate *date = [myCustomFormatter dateWithString:italianDate locale:italianLocale];
I struggled with German formats as well sometime ago and solved the problem by supplying my own formatting string:
[formatter setDateFormat:#"dd.MMM.yyyy HH:mm:ss"];
Then:
[dateFormatter dateFromString:#"01.Dez.2010 15:03:00"];
will get a correct NSDate.

NSDateFormater from NSMutableArray value

I store some dates in my NSMutableArray, I want to retrieve them and change the format.
For the moment I do this:
NSDate *myDate = [self.dates objectAtIndex:0];
NSLog(#"myDate:%#", myDate); // 2010-03-02
NSDateFormatter *formatDate = [[NSDateFormatter alloc] init];
[formatDate setDateFormat:#"MMMM d YYYY"];
NSString *newDate = [formatDate stringFromDate:myDate];
NSLog(#"newDate: %#", newDate); // NULL
the result for newDate is NULL, and I want it to be something like that: "March 3, 2010"
thanks,
That works for me, but I replaced the first line with:
NSDate *myDate = [NSDate date];
My output:
2010-03-02 19:29:08.045 app[11464:a0f] myDate:2010-03-02 19:29:08 -0800
2010-03-02 19:29:08.048 app[11464:a0f] newDate: March 2 2010
My best guess is that [self.dates objectAtIndex:0] isn't returning what you want it to.
Since your dates array contains strings, you have to convert the string to an NSDate and then you can re-convert the date to the format you want.
NSDateFormatter *strToDateFmt = [[NSDateFormatter alloc] init];
[strToDateFmt setDateFormat:#"yyyy-MM-dd"];
NSDate *myDate = [strToDateFmt dateFromString:[self.dates objectAtIndex:0]];
[strToDateFmt release];
NSLog(#"myDate:%#", myDate);
NSDateFormatter *formatDate = [[NSDateFormatter alloc] init];
[formatDate setDateFormat:#"MMMM d YYYY"];
NSString *newDate = [formatDate stringFromDate:myDate];
[formatDate release];
NSLog(#"newDate: %#", newDate);

How to handle different date time formats using NSDateFormatter

I have a String with a datetime format: "YYYY-MM-DD HH:MM:SS".
I use this in my source code:
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"%e. %B %Y"];
NSString *test = [formatter stringFromDate:#"2010-01-10 13:55:15"];
I want to convert from "2010-01-10 13:55:15" to "10. January 2010".
But my implementation does not work.
What's wrong here?
Thanks a lot in advance & Best Regards.
Updated source code:
[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4];
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"%Y-%m-%d %H:%M:%S"];
NSString *test1 = [formatter stringFromDate:#"2010-01-10 13:55:15"];
NSDateFormatter *formatter1 = [[[NSDateFormatter alloc] init] autorelease];
[formatter1 setDateFormat:#"%d. %M4 %Y"];
NSString *test2 = [formatter1 stringFromDate:test1];
A date formatter can only handle one format at a time. You need to take this approach:
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [f dateFromString:#"2010-01-10 13:55:15"];
NSDateFormatter *f2 = [[NSDateFormatter alloc] init];
[f2 setDateFormat:#"d. MMMM YYYY"];
NSString *s = [f2 stringFromDate:date];
s will now be "10. January 2010"
Here are a few examples of working with data formatters from my code. You should be able to take any one of these functions and tweak it for your format.
USAGE
NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [Constants getTitleDateFormatter];
NSString *dateString = [dateFormatter stringFromDate:today];
[dateFormatter release];
FUNCTIONS
+ (NSDateFormatter *) getDateFormatterWithTimeZone {
//Returns the following information in the format of the locale:
//YYYY-MM-dd HH:mm:ss z (Z is time zone)
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[NSLocale currentLocale]];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
[dateFormatter setTimeStyle:NSDateFormatterLongStyle];
return dateFormatter;
}
+ (NSDateFormatter *)dateFormatterWithoutYear {
NSDateFormatter *dateFormatter = [Constants getDateFormatterWithTimeZone];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSString *format = [dateFormatter dateFormat];
format = [format stringByReplacingOccurrencesOfString:#"/yy" withString:#""];
NSRange secondSpace;
secondSpace.location = format.length-2;
secondSpace.length = 1;
format = [format stringByReplacingCharactersInRange:secondSpace withString:#""];
[dateFormatter setDateFormat:format];
return dateFormatter;
}
+ (NSDateFormatter *) dateFormatterMonthDayOnly {
NSDateFormatter *dateFormatter = [Constants getDateFormatterWithTimeZone];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSString *format = [dateFormatter dateFormat];
format = [format stringByReplacingOccurrencesOfString:#"/yy" withString:#""];
NSRange range;
range.location = 0;
range.length = 3;
format = [format substringWithRange:range];
[dateFormatter setDateFormat:format];
return dateFormatter;
}
+ (NSDateFormatter *) getTitleDateFormatter {
//Returns the following information in the format of the locale:
//MM-dd-yyyy hh:mm:ssa
NSDateFormatter *dateFormatter = [Constants getDateFormatterWithTimeZone];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
NSString *format = [dateFormatter dateFormat];
NSRange secondSpace;
secondSpace.location = format.length-2;
secondSpace.length = 1;
format = [format stringByReplacingOccurrencesOfString:#"/" withString:#"-"];
format = [format stringByReplacingCharactersInRange:secondSpace withString:#""];
[dateFormatter setDateFormat:format];
return dateFormatter;
}
First off, make sure you set the behavior to 10.4 - more modern, works better in my experience.
[dateTimeFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
Next, you can't use the same format to parse and format if they have 2 different string representations, so use 2 formatters, or change the string format between parsing and then formatting.
Also make sure you consider the formatting options:
http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW1
lowercase is e is the day of week, lowercase d is the day of the month.
For month, use MMMM, not B.
You want to use [NSFormatter dateFromString:] to convert your string-based date to an NSDate instance. From there you want to use stringFromDate with the NSDate, not the string as you have written above. I'm not sure about using the same NSDateFormatter for both parsing and formatting - you may need two separate instances to handle the different format styles.