ios: String to Date conversion - iphone

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);

Related

How to convert time in 24 hr format in iphone?

I have to convert the given time in 24 hr format.But I did not get it.Don't know where I m going wrong.
If I have TimeStart as 1:15 PM then I should get 13:15 ..
Item *item=[sectionItems objectAtIndex:itemId];
NSLog(#"%#",item.TimeStart);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm a"];
NSString *formattedDateString = [dateFormatter stringFromDate:item.TimeStart];
NSLog(#"%#",formattedDateString);
In the code above I have a Item class and that I have NSString *TimeStart;
When I see formattedDateString it is returning null.How can I fix it ?
Item *item=[sectionItems objectAtIndex:itemId];
NSLog(#"%#",item.TimeStart);
NSString *str = #"1:45.PM";// put here item.TimeStart
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"hh:mm.a"];// here give the format which you get in TimeStart
NSDate *date = [dateFormatter dateFromString: str];
dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"HH:mm"];
NSString *convertedString = [dateFormatter stringFromDate:date];
NSLog(#"Converted String : %#",convertedString);
i just simply setDateFormat like [formatter setDateFormat:#"HH:mm"]; Remove a
and below caode for checking its time formate is 24 hr or 12
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setLocale:[NSLocale currentLocale]];
[formatter setDateStyle:NSDateFormatterNoStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
NSString *dateString = [formatter stringFromDate:[NSDate date]];
NSRange amRange = [dateString rangeOfString:[formatter AMSymbol]];
NSRange pmRange = [dateString rangeOfString:[formatter PMSymbol]];
BOOL is24h = (amRange.location == NSNotFound && pmRange.location == NSNotFound);
[formatter release];
NSLog(#"%#\n",(is24h ? #"YES" : #"NO"));
Use this to set 24 hr format.
[currentDate setDateFormat:#"yyyy-MM-dd HH:mm"];
or
[formatter setDateFormat:#"HH:mm"];
without using formatter
NSRange range;
range.location = 2;
range.length = 2;
NSString *dateString=[NSString stringWithFormat:#"%#:%#",[myString substringToIndex:2], [myString substringWithRange:range]];
This is the code i am using in my project and its working for me
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"HH:mm"];
NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
NSLog(#"Current time date:%#", dateString);
output:Current time date:14:41

Retrieving hours in 24 hour format in iphone

I am using this format to get hours
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"hh";
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
NSString *date = [dateFormatter stringFromDate:now];
NSInteger myHour = [date intValue];
The problem is it returns e.g 4Pm i Want it to return 16 Instead of 4. How can I do that? I tried replacing hh by single h by of no avail.
Here Your input:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"hh"];
NSDate *Yourcurrenttime = [dateFormatter dateFromString:Yourstring];
And date converted to the String ..
[dateFormatter setDateFormat:#"HH"];
NSString *date = [dateFormatter stringFromDate:now];
NSInteger myHour = [date intValue];
Here is answer :-
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"HH";
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
NSString *date = [dateFormatter stringFromDate:[NSDate date]];
NSInteger myHour = [date intValue];
NSLog(#"%d",myHour);
Hope it helps you!
Its for 12 hour time format :-
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:#"hh a"];
NSString *theTime = [timeFormat stringFromDate:[NSDate date]];
NSLog(#"time, %#",theTime);
Its for 24 hour time format:-
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:#"HH"];
NSString *theTime = [timeFormat stringFromDate:[NSDate date]];
NSLog(#"time, %#",theTime);

String to Date Conversion in iPhone

I have refer previous examples from here. But still problem in null value.
String Value is :==> strDate = "09-05-2012 00:00:00"
I want output as :==> May 09, 2012
My Code:
NSString *strDateFormat;//[strDate substringWithRange:NSMakeRange(0, 10)];
strDateFormat = [NSString stringWithFormat:#"%#", strDate];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
NSDate *disDate = [df dateFromString:strDateFormat];
[df setDateFormat:#"MMM dd, yyyy"];
strDateFormat = [df stringFromDate:disDate];
lblDate.text = [NSString stringWithFormat:#"%#", strDateFormat];
[df release];
It gives (null) value. Because disDate has (null) value.
Why disDate set to nil..?
Any solution..?
You gotta tell the formatter what format to expect when reading a string, too.
NSString *string = #"09-05-2012 00:00:00";
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [formatter dateFromString:string];
[formatter setDateFormat:#"MMM dd, yyyy"];
NSString *formattedString = [formatter stringFromDate:date];
-(NSString*)getStringWithFormat:(NSString*)pStrDate fromFormat:(NSString*)pFromFormat toFormat:(NSString*)pToFormat
{
NSDateFormatter *dtFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dtFormatter setDateFormat:pFromFormat];
NSDate *fromFormatDate = [dtFormatter dateFromString:pStrDate];
[dtFormatter setDateFormat:pToFormat];
return [dtFormatter stringFromDate:fromFormatDate];
}
and call it like this
NSString *strDate = [self getStringWithFormat:#"09-05-2012 00:00:00" fromFormat:#"dd-MM-yyyy HH:MM:SS" toFormat:#"MMM dd, yyyy"];
This is common function, You can use it for any formats, Just you have to pass that format in argument.
NSString *strDateFormat; //[strDate substringWithRange:NSMakeRange(0, 10)];
strDateFormat = [NSString stringWithFormat:#"%#", strDate];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"MMM dd, yyyy"];
// ###### Set dateformat also here according to strDateFormat
NSDate *disDate = [df dateFromString:strDateFormat];
[df setDateFormat:#"MMM dd, yyyy"];
strDateFormat = [df stringFromDate:disDate];
lblDate.text = [NSString stringWithFormat:#"%#", strDateFormat];
[df release];
you have not set the formater pattern
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setFormatterBehavior:NSDateFormatterBehavior10_4];
[df setDateFormat:#"MMM dd, yyyy"];
NSDate *convertedDate = [df dateFromString:origDate];
[df release];

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.

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.