How can I parse out date and time separately from a string? - objective-c

I have a string in the format "3 Dec 2012 1:00PM" and I need to parse out date and time so that I can get "3 Dec 2012" and "1:00PM" in separate NSStrings. How would I do that?

NSString *strInput = #"3 Dec 2012 1:00PM";
static NSString *format = #"dd MMM yyyy hh:mma";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"GMT"]];
[dateFormatter setDateFormat:format];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
[dateFormatter setLocale:usLocale];
NSDate *date = [dateFormatter dateFromString:strInput];
static NSString *format1 = #"dd MMM yyyy";
[dateFormatter setDateFormat:format1];
NSString *strDatePart1 = [dateFormatter stringFromDate:date]; // gives 3 Dec 2012
static NSString *format2 = #"hh:mma";
[dateFormatter setDateFormat:format2];
NSString *strDatePart2 = [dateFormatter stringFromDate:date]; // gives 1:00PM

The easiest (and fastest) way for this issue is to use it as string without date formatter:
NSArray* components = [fullDateTime componentsSeparatedByString:#" "];
NSString* date = [NSString stringWithFormat:#"%#%#%#", [components objectAtIndex:0], [components objectAtIndex:1], [components objectAtIndex:2]];
NSString* time = [components objectAtIndex:3];

Try this...this may help you..
NSDateFormatter *formatOld = [[NSDateFormatter alloc] init];
[formatOld setDateFormat:#"dd MMM yyyy hh:mma"]; //3 Dec 2012 1:00PM
NSString *oldDate = #"3 Dec 2012 1:00PM";
NSDate *date = [formatOld dateFromString:oldDate];
NSDateFormatter *newFormate = [[NSDateFormatter alloc]init];
[newFormate setDateFormat:#"dd MMM yyyy 'and' hh:mm a"]; //3 Dec 2012" and "1:00PM
NSString *newdate =[newFormate stringFromDate:date];
NSLog(#"%#",newdate);

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd MMM YYYY"];
NSDate *date = [NSDate date];
//in your case you have a string in place of date. I have made it generalised.
//if you have string
NSString *onlyDate = [dateFormatter stringFromDate:date];
NSLog(#"Date: %# ", onlyDate);
[dateFormatter setDateFormat:#"hh:mm a"];
NSString *onlyTime=[dateFormatter stringFromDate:date];
NSLog(#"Time: %# ", onlyTime);
Outputs
Date: 27 Nov 2012
Time: 02:43 PM

NSString* dateString = #"3 Dec 2012 1:00PM";
- (int) indexOf:(NSString*)source of:(NSString *)text {
NSRange range = [source rangeOfString:text];
if ( range.length > 0 ) {
return range.location;
} else {
return -1;
}
}
-(void)dostrip{
NSString* date = [dateString substringToIndex:[self indexOf:#":"]];
NSLog(#"date: %#", date);
NSString* hour = [dateString substringFromIndex:[self indexOf:#":"]];
NSLog(#"hour: %#", hour);
}
`

Related

iOS set default date to date picker?

I've a date picker associated with a text field.Text field has value like this Thursday, November 22nd(string recieved from server call).
Now i want that when i click on text field date picker should sow default date that is displayed in text field.
I guess i've to call [datePicker setDate:date animated:YES]; but problem is that how to convert string Thursday, November 22nd into NSDate?
Thanks in advance.
I assume u would like current year in your date:
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy"];
NSString *yeardate = [dateFormat stringFromDate:[NSDate date]];
NSString *string = #"Thursday, November 22nd";
if ( [string length] > 0)
string = [string substringToIndex:[string length] - 2];
NSString *finalstr = [NSString stringWithFormat:#"%# %#",string,yeardate];
[dateFormat setDateFormat:#"EEEE,MMMM dd yyyy"];
NSDate *date = [dateFormat dateFromString:finalstr];
NSLog(#"%#",date);
You can follow the code snippet below
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"EEEE MMMM d, yyyy"];
NSString *dateStr;
NSDate *date;
date = [NSDate date];
dateStr= [formatter stringFromDate:date];
NSLog(#"%#", dateStr); // -> Tuesday November 6, 2012
dateStr= #"Tuesday November 6, 2012";
date = [formatter dateFromString:dateStr];
NSLog(#"%#",date); // -> 2012-11-05 18:15:00 +0000

NSDateFormatter and NSString to NSDate conversion

Good day, I'm trying to convert NSString that I'm getting from the server to NSDate object.
That is the code:
NSString *date = #"Sep 12 at 12:03 am";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MMM d 'at' H:m a"];
self.messageDateAndTime = [dateFormatter dateFromString:date];
NSLog(#"NSDate: %#", self.messageDateAndTime);
I'm getting date in the format that date string has. After I'm trying to create my own formatter for this date format. But anyway, I'm getting null! What I'm doing wrong?
I debug you above code its running fine and giving NSDate: 1970-09-11 18:33:00 +0000 this log. Check for you string first. For more you can use the category below.
// NSString+Date.h
#interface NSString (Date)
+ (NSDate*)stringDateFromString:(NSString*)string;
+ (NSString*)stringDateFromDate:(NSDate*)date;
#end
// NSString+Date.m
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:#"EEE, dd MMM yyyy HH:mm:ss ZZZ"];
NSDate *date = [dateFormatter dateFromString:stringDate ];
[dateFormatter release];
+ (NSDateFormatter*)stringDateFormatter
{
static NSDateFormatter* formatter = nil;
if (formatter == nil)
{
formatter = [NSDateFormatter alloc] init];
[formatter setDateFormat:#"EEE, dd MMM yyyy HH:mm:ss ZZZ"];
}
return formatter;
}
+ (NSDate*)stringDateFromString:(NSString*)string
{
return [[NSString stringDateFormatter] dateFromString:string];
}
+ (NSString*)stringDateFromDate:(NSDate*)date
{
return [[NSString stringDateFormatter] stringFromDate:date];
}
// Usage (#import "NSString+Date.h")
NSString* string = [NSString stringDateFromDate:[NSDate date]];
NSDate* date = [NSString stringDateFromString:string];
Please find the correct NSDateFormatter formatting string here.
I found the solution my self, it would return null until you set the locale yourself. This is the code:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
[dateFormatter setLocale:usLocale];
[dateFormatter setDateFormat:#"MMM d 'at' H:m a"];
self.messageDateAndTime =[dateFormatter dateFromString:messageDate];

NSDate formatting it to include Date and Time

I have two strings.
NSString *dateof = #"Mon May 21";
NSString *timeof = #"01.00 pm from 11.50 pm"; // 01.00 pm is the start time and 11.50 pm is the end time
I need to save these as NSDates, in the format , so that it will be 2012-05-21 13:00:00 +0000.
My approach so far has been:
NSDate *currentTime = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents
*currentDateComps = [cal components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
fromDate:currentTime];
NSString *startDateStringWithYear = [NSString stringWithFormat:#"%# %d", startDateString, currentDateComps.year];
NSString *endDateStringWithYear = [NSString stringWithFormat:#"%# %d", endDateString, currentDateComps.year];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"EEE MM dd yyyy"];
[formatter setTimeZone:[NSTimeZone systemTimeZone]];
NSDate *startDate = [formatter dateFromString:startDateStringWithYear];
NSArray *timeDurationStringWords = [timeof componentsSeparatedByString:#" "];
// Calculate NSDate's for the start time for today:
NSString *startTimeString = [timeDurationStringWords objectAtIndex:0];
currentDateComps.hour = [[startTimeString substringToIndex:2] intValue];
currentDateComps.minute = [[startTimeString substringFromIndex:3] intValue];
if ([[timeDurationStringWords objectAtIndex:1] isEqualToString:#"pm"])
{
currentDateComps.hour += 12;
}
NSDate *startTime = [cal dateFromComponents:currentDateComps];
When I debug the code, startTime prints as 2012-05-29 07:30:00 +0000 which is incorrect (both the day and time are incorrect). I think this is because of the GMT time.
I need the date and time to be 2012-05-21 13:00:00 +0000.
This will do it. As far as the local/GMT, this will give you a NSDate that contains the local time but the debugger will show always show it in GMT. You will need to format it (using a NSDateFormatter) into the format that you want if you are going to show it to the user, in which case it will be in local time.
NSString *dateof = #"Mon May 21";
NSString *timeof = #"01.00 pm from 11.50 pm";
NSDate *today = [NSDate date];
// Start time will be array index 0, end time will be index 1:
NSArray *times = [timeof componentsSeparatedByString:#" from "];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *yearComp = [cal components:NSYearCalendarUnit fromDate:today];
// Append the year and the time to the dateof string to get a string like #"Mon May 21 2012 01.00 pm":
NSString *start = [dateof stringByAppendingFormat:#" %d %#", yearComp.year, [times objectAtIndex:0]];
NSString *end = [dateof stringByAppendingFormat:#" %d %#", yearComp.year, [times objectAtIndex:1]];
// Make a date formatter that recognizes the above date/time:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"EEE MMM dd yyyy hh.mm a"];
// Convert the strings to dates:
NSDate *startDate = [formatter dateFromString:start];
NSDate *endDate = [formatter dateFromString:end];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd 'at' HH:mm"];
NSString *str = [formatter stringFromDate:[NSDate date]];
NSLog(#"str=%#",str);
NSDate *dt = [NSDate date];
dt = [formatter dateFromString:str];
NSLog(#"dt=%#",dt);
Output:
str=2012-05-29 at 10:36
dt=2012-05-29 05:06:00 +0000

NSDateFormatter with RSS pubDate

I have some problems with converting a rss pubdate string into a NSDate object.
<pubDate>Fri, 09 Sep 2011 15:26:08 +0200</pubDate>
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"EEE, d MMM yyyy HH:mm:ss Z"];
NSDate *date = [dateFormatter dateFromString:currentDate];
NSLog(#"DateObject : '%#'", date);
[dateFormatter release];
I always get
[44157:10d03] DateObject : '(null)'
You'll need:
dd instead of d, since the day is zero-padded
ZZ instead of Z, since it doesn't include the timezone abbreviated name
More info: http://unicode.org/reports/tr35/tr35-4.html#Date_Format_Patterns
When I run this:
int main (int argc, const char * argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *str = #"Fri, 09 Sep 2011 15:26:08 +0200";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"EEE, dd MMM yyyy HH:mm:ss ZZ"];
NSDate *date = [dateFormatter dateFromString:str];
NSLog(#"DateObject : %#", date);
[dateFormatter release];
[pool drain];
return 0;
}
I get this:
EmptyFoundation[19926:407] DateObject : 2011-09-09 13:26:08 +0000
First you could try the following code:
NSString *str = #"Mon, 19 Oct 2015 14:27:28 +0800";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"EEE, dd MMM yyyy HH:mm:ss ZZ"];
NSDate *date = [dateFormatter dateFromString:str];
NSLog(#"DateObject : %#", date);
However, If your DateObject is still null , your locale is not correctly located "en_US_POSIX" format. You need change your locale.
NSString *str = #"Mon, 19 Oct 2015 14:27:28 +0800";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"EEE, dd MMM yyyy HH:mm:ss ZZ"];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
[dateFormatter setLocale:enUSPOSIXLocale];
NSDate *date = [dateFormatter dateFromString:str];
NSLog(#"DateObject : %#", date);
The result is:
DateObject : 2015-10-19 06:27:28 +0000
Use :
NSArray *array=[string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
to split the pubDate by whitespaces and newline and then get every element you want to show by using the indexes of the array.
I use this code to format Wordpress RSS feed dates:
+ (NSDate *)parseWordpressDate:(NSString *)dataWp {
NSArray *array=[dataWp componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
//Tue, 04 Mar 2014 11:00:36 +0000
//day = index 1, month = 2, year = 3
NSString *yyear = [array objectAtIndex:3];
NSString *mmonth = [array objectAtIndex:2];
NSString *dday = [array objectAtIndex:1];
NSDateFormatter *dateFormatterGMTAware = [[NSDateFormatter alloc] init];
[dateFormatterGMTAware setDateFormat:#"yyyy-MMM-dd"];
NSString *dateString = [NSString stringWithFormat:#"%#-%#-%#",yyear,mmonth,dday];
NSDate *data = [dateFormatterGMTAware dateFromString:dateString];
return data;
}

Converting a string to an NSDate

How is it possible to convert a string to an NSDate on iOS?
NSString *dateStr = #"20100223";
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyyMMdd"];
NSDate *date = [dateFormat dateFromString:dateStr];
// Convert date object to desired output format
[dateFormat setDateFormat:#"EEEE MMMM d, YYYY"];
dateStr = [dateFormat stringFromDate:date];
[dateFormat release];
Hope this will help you.
You'll want to take a look at NSDateFormatter. Determine the format of the date string and then use dateFromString: to convert the string to an NSDate object.
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd/MM/YYYY"];
NSDate *date = [dateFormat dateFromString:dateStr];
list = [self getYear:date];
- (NSMutableArray *)getYear:(NSDate*)date
{
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:date];
int year = [components year];
int month = [components month];
int day = [components day];
NSLog(#"%d",year);
NSMutableDictionary *dateDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:#"%d", day], #"day", [NSString stringWithFormat:#"%d", month], #"month", [NSString stringWithFormat:#"%d", year], #"year", nil];
return dateDict;
}
My working version in Swift
func dateFor(timeStamp: String) -> NSDate
{
let formater = NSDateFormatter()
formater.dateFormat = "HH:mm:ss:SSS - MMM dd, yyyy"
return formater.dateFromString(timeStamp)!
}
func timeStampFor(date: NSDate) -> String
{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH:mm:ss:SSS - MMM dd, yyyy"
return dateFormatter.stringFromDate(date)
}
A simple approach even if you have sqlite DB:
// NSTimeInterval is basically typedef of double so you can receive it as double also.
NSTimeInterval *current = [[NSDate date] timeIntervalSince1970];
[DB addToDB:current];
//retrieve the date from DB
NSDate *retrievedDateItem = [[NSDate alloc] initWithTimeIntervalSince1970:[getDBValueAsDouble]]; //convert it from double (NSTimeInterval) to NSDate
// Set the style
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
// Converted to string
NSString *convertedDate = [dateFormatter stringFromDate:retrievedDateItem];
The output for this example:
Aug 3, 2015, 12:27:50 PM
+(NSDate*)str2date:(NSString*)dateStr{
if ([dateStr isKindOfClass:[NSDate class]]) {
return (NSDate*)dateStr;
}
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd"];
NSDate *date = [dateFormat dateFromString:dateStr];
return date;
}