Converting a string to an NSDate - objective-c

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

Related

we get string form web service that string how to convert NsString to NSDate in objective c?

i have tried like this
cell.msgid.text=[[tableArray objectAtIndex:indexPath.row]objectForKey:#"MobileMessageMasterId"];
NSString *datefromweb= [[tableArray objectAtIndex:indexPath.row] objectForKey:#"MessageDateTime"];
NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
[dateformatter setDateFormat:#"dd/MM/yyyy hh:mm:ss"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateformatter dateFromString:datefromweb];
[dateformatter setDateFormat:#"MMM yyyy"];
NSString *month1 = [dateformatter stringFromDate:dateFromString];
[dateformatter setDateFormat:#"hh:mm a"];
NSString *time= [dateformatter stringFromDate:dateFromString];
[dateformatter setDateFormat:#"dd"];
NSString *day1= [dateformatter stringFromDate:dateFromString];
we get string in datefromweb(NSString) variable but not get in
datefromstring(NSDate) variable and i am separate out date,time,month,year.
my response is
{ MessageDateTime = "19/01/2016 14:16:03";}
Try like this:
NSString *yourString = #""; // use your string here where you will get from JSON
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setTimeZone:[NSTimeZone localTimeZone]]; // Set timezone whatever you want
[formatter setDateFormat:#"dd/MM/yyyy HH:mm:ss"];
NSDate *convertedDate = [formatter dateFromString:yourString];
NSLog(#"%#",convertedDate);
//Get Date string from web
NSString *datefromweb= #"19/01/2016 14:16:03";
//Set Date Formatter
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"dd/MM/yyyy HH:mm:ss"];
//Convert string into Date
NSDate *selectedDate = [df dateFromString: datefromweb];
//For Setting new format to NSDate need to create new NSDateFormatter.
NSDateFormatter *df1 = [[NSDateFormatter alloc] init];
[df1 setDateFormat:#"dd"];
NSString* myDayString = [df1 stringFromDate:selectedDate];
[df1 setDateFormat:#"MMM"];
NSString* myMonthString = [df1 stringFromDate:selectedDate];
[df1 setDateFormat:#"MM"];
NSString* myMonthString1 = [df1 stringFromDate:selectedDate];
[df1 setDateFormat:#"yyyy"];
NSString* myYearString = [df1 stringFromDate:selectedDate];
[df1 setDateFormat:#"hh:mm a"];
NSString* myTimeString = [df1 stringFromDate:selectedDate];
Output :
Date 19
Month Name Jan - 01
Year 2016
Time 02:16 PM
Use NSDateComponents is better approach
NSDateFormatter *formatter = [NSDateFormatter new];
[formatter setDateFormat:#"dd/mm/yyyy HH:mm:ss"];
NSDate *date = [formatter dateFromString:#"19/01/2016 14:16:03"];
NSCalendar *gregorian = [NSCalendar currentCalendar];
NSDateComponents *comonents =
[gregorian components:(NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond
) fromDate:date];
NSInteger day = [comonents day];
NSInteger month = [comonents month];
NSInteger year = [comonents year];
NSInteger hour = [comonents hour];
NSInteger minutes = [comonents minute];
NSInteger seconds = [comonents second];

How to convert Nstring to NSDate?

i want to convert nsstring to nsdate
i have string have this value
08:00:00
i want to convert it so i wrote this code
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"HH:mm:ss"];
NSDate *startDate = [formatter dateFromString:_startTime];
NSLog(#"%#",startDate);
_startTime have this value = 08:00:00
but startDate after i display it , it had this value
2000-01-01 06:00:00 +0000
Update I wrote this code
NSString *dateString = _startTime;
NSDateFormatter *formatter= [[NSDateFormatter alloc] init];
// this is imporant - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[formatter setDateFormat:#"HH:mm:ss"];
NSDate *startDate = [[NSDate alloc] init];
// voila!
startDate = [formatter dateFromString:dateString];
NSLog(#"%#",startDate);
i want the output be 08:00:00
You can't have NSDate without a date !
if you want to access the time from an NSDate you'll need to use NSDateComponents (or NSTimeInterval).
To access the time from your NSDate using NSDateComponents :
NSString *startTime = #"08:00:00";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"HH:mm:ss"];
NSDate *startDate = [formatter dateFromString:startTime];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:startDate];
NSLog(#"%d:%d:%d", [components hour], [components minute], [components second]);
I don't get what's the purpose of changing the string _startTime, do you want to compare dates ?
Edit :
NSString *startTime = #"08:00:00";
NSString *endTime = #"23:00:00";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"HH:mm:ss"];
NSDate *startDate = [formatter dateFromString:startTime];
NSDate *endDate = [formatter dateFromString:endTime];
NSTimeInterval difference = [endDate timeIntervalSinceDate:startDate];
NSInteger temp = difference;
NSDate* newDate = [[NSDate alloc] init];
for (int i = 0; (i < difference && [newDate compare:startDate] == NSOrderedDescending); ++i)
{
newDate = [startDate dateByAddingTimeInterval:(temp - i*60*10)];
NSLog(#"%#",newDate);
}
run this and use NSDateComponents to log what you want !
Use this code i think this one help you..
NSString *dateStr = #"08:00:00";
NSDateFormatter *datFormatter = [[NSDateFormatter alloc] init];
[datFormatter setDateFormat:#"HH:mm:ss"];
NSDate* mydate = [datFormatter dateFromString:dateStr];
NSLog(#"date: %#", [datFormatter stringFromDate:mydate]);
i think this is what you really want...

Converting to and from NSDate causes crash

I am trying to convert a NSString to a date, add a day to it, then convert back to a string.
My code so far is this:
//convert curDate (from #property declaration) to NSDate
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:curDate];
//add a day
dateFromString = [dateFromString dateByAddingTimeInterval:60*60*24*1];
//convert back to string (for use in URL string concatenation)
NSString *dateDisplay = [dateFormatter stringFromDate:dateFromString];
//set curDate to new date
curDate = dateDisplay;
It crashes to the stack at:
0x117f09b: movl 8(%edx), %edi
(not sure if that's useful).
Can anyone say why this is?
Thanks!
You should use NSDateComponents:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSDate *dateFromString = [dateFormatter dateFromString:self.curDate];
// Create components
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
dateComponents.day = 1;
// Get the calendar to add the components to a date
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *incrementedDate = [calendar dateByAddingComponents:dateComponents toDate:dateFromString options:0];
NSString *dateDisplay = [dateFormatter stringFromDate:incrementedDate];
//set curDate to new date
curDate = dateDisplay;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
//add a day
NSDate *dateFromString = [[NSDate date] dateByAddingTimeInterval:60*60*24*1];
//convert back to string (for use in URL string concatenation)
NSString *dateDisplay = [dateFormatter stringFromDate:dateFromString];

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