Date and Time Format in iOS application - ios

I am getting below date format from response
2015-12-23 05:17:04
But, I want to check date and time like,
date == today ?
date == yesterday ?
time == 1 hour
time == 2 hour till 9 hour
how to do it ?

To check whether date is today's, yesterday's, tomorrow's date etc... you can use NSDate-Extensions
ex:
NSDate *date = [self convertStringToDate:#"2015-12-24 12:40:04" formate:#"yyyy-MM-dd HH:mm:ss"];
NSLog(#"%d", [date isToday]);
NSLog(#"%d", [date isTomorrow]);
NSLog(#"%d", [date isYesterday]);
- (NSDate *)convertStringToDate: (NSString *)date formate:(NSString *)formate {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US"]];
[dateFormat setDateFormat:formate];
return [dateFormat dateFromString:date];
}

Use this method give you NSString back. you can compare string or time in method.
-(NSString* )AgoStringFromTime:(NSDate*)dateTime
{
NSDictionary *timeScale = #{#"sec" :#1,
#"min" :#60,
#"hr" :#3600,
#"day" :#86400,
#"week" :#605800,
#"month":#2629743,
#"year" :#31556926};
NSString *scale;
int timeAgo = 0-(int)[dateTime timeIntervalSinceNow];
if (timeAgo < 60) {
scale = #"sec";
} else if (timeAgo < 3600) {
scale = #"min";
} else if (timeAgo < 86400) {
scale = #"hr";
} else if (timeAgo < 605800) {
scale = #"day";
} else if (timeAgo < 2629743) {
scale = #"week";
} else if (timeAgo < 31556926) {
scale = #"month";
} else {
scale = #"year";
}
timeAgo = timeAgo/[[timeScale objectForKey:scale] integerValue];
NSString *s = #"";
if (timeAgo > 1) {
s = #"s";
}
return [NSString stringWithFormat:#"%d %#%#", timeAgo, scale, s];
}

NSDate *date = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = [NSString stringWithFormat:#"yyyyMMddHHmmss"];
NSString *now = [dateFormatter stringFromDate:date];
You can try above code
Best wish

1.frist you can format your string to date,like this:
+ (NSDate *)dateFromString:(NSString *)dateString {
if (!dateString) {
return nil;
}
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat: #"yyyy-MM-dd HH:mm:ss"];
[formatter setLocale:[NSLocale currentLocale]];
NSDate *date= [formatter dateFromString:dateString];
return date;
}
2.then,you can use methods of NSDate,
+ (instancetype)date;//get current
- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)refDate;//Returns the interval between the receiver and another given date.

Related

Converting String to Time Format returns nil Data

My Json is
{
"MinPerAppointment": "30",
"OpeningTime": "12:05"
}
Now, I want to Add 30 to 12:05, which Should be 12:35, I could not get How to format it, SO, I tried it with NSdate
NSString *str_MinPerAppointment = timeDetailData.minPerAppointment;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm"];
NSDate *myDate = [dateFormatter dateFromString:str_MinPerAppointment];
NSString *dateInString = [dateFormatter stringFromDate:myDate];
NSLog(#"New AppointMentValue :%#",dateInString);
I am getting New AppointMentValue as nil.
I don't think you need to use NSDate formatting. Simply convert HH:MM to minutes (or seconds, if you deal with them), do your math and then convert back.
Something like:
NSString *time = #"12:30";
int addMinutes = 30;
int hh, mm;
if (sscanf([time UTF8String], "%d:%d", &hh, &mm) == 2) {
int minutes = (hh * 60) + mm;
minutes += addMinutes;
hh = minutes / 60;
mm = minutes - (hh * 60);
hh %= 24; // day roll-over
NSString *newTime = [NSString stringWithFormat:#"%02:%02d", hh, mm];
} else {
NSLog(#"Invalid time value: %#", time);
}
If you want to use NSDateFormatter/NSDate try this-
NSString *str_MinPerAppointment = #"30";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm"];
NSDate *myDate = [dateFormatter dateFromString:#"12:05"] ;
NSString *dateInString = [dateFormatter stringFromDate:[myDate dateByAddingTimeInterval:60*[str_MinPerAppointment integerValue]]];
NSLog(#"New AppointMentValue :%#",dateInString);

how to check current date time is in between given date times in iOS? [duplicate]

This question already has answers here:
How to Check if an NSDate occurs between two other NSDates
(10 answers)
Closed 6 years ago.
I have to check my current date time is in between the given 2 set of date time (need to check both time and date part of NSDate).
Here is my code
NSString *startingDate = [[[vehicle timeRestrictions] objectAtIndex:i] valueForKey:#"start_ts"];
NSString *endingDate = [[[vehicle timeRestrictions] objectAtIndex:i] valueForKey:#"end_ts"];
NSDate *startDate = [NSDate dateWithTimeIntervalSince1970:[startingDate longLongValue]/1000];
NSDate *endDate = [NSDate dateWithTimeIntervalSince1970:[endingDate longLongValue]/1000];
NSLog(#"Start Date %#",startDate);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init] ;
[dateFormatter setDateFormat:#"dd-MM-yyyy HH:mm:ss a"]; // here replace your format dd.MM.yyyy
NSLog(#"result: %#", [dateFormatter stringFromDate:[NSDate date]]);
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
// [dateFormat setDateFormat:#"YYYY-MM-dd\'T\'HH:mm:ss ssZZZZZ"];
[dateFormat setDateFormat:#"dd-MM-yyyy HH:mm:ss "];
BOOL checkVehicleRestriction = [self getDatePartForRestriction:[dateFormat stringFromDate:startDate] :[dateFormat stringFromDate:endDate]];
-(BOOL)getDatePartForRestriction:(NSString *)date :(NSString *)endDate{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"YYYY-MM-dd\'T\'HH:mm:ssZZZZZ"];
[dateFormat setDateFormat:#"dd-MM-yyyy HH:mm:ss"];
NSLog(#"%# - %#",date,endDate);
if([self isDate:[NSDate date] inRangeFirstDate:[dateFormat dateFromString:date] lastDate:[dateFormat dateFromString:endDate]]){
return YES;
}
return NO;
}
- (BOOL)isDate:(NSDate *)date inRangeFirstDate:(NSDate *)firstDate lastDate:(NSDate *)lastDate {
return !([date compare:firstDate] == NSOrderedAscending) && !([date compare:lastDate] == NSOrderedDescending);
}
When I run this code i am always getting YES for checkVehicleRestriction .
These are the date time format am using 02-06-2016 20:09:47 PM
I'm not sure how you are calculating your startDate and end Date, but to simply calculate if your current date is in between two dates or not, you can do this:
Get the dates:
NSString *startingDate = #"01-06-2016 20:09:47 PM";
NSString *endingDate = #"08-06-2016 20:09:47 PM";
NSDateFormatter *startForm=[[NSDateFormatter alloc]init];
[startForm setDateFormat:#"dd-MM-yyyy HH:mm:ss a"];
NSDate *startDate = [startForm dateFromString:startingDate];
NSDate *endDate = [startForm dateFromString:endingDate];
and to check if current date is in between two dates
Date1(before current) CurrentDate Date2(after current) = CurrentDate is in Range
Date2(before current) CurrentDate Date1(after current) = CurrentDate is in Range
So we need to check for only two cases
case A - (startDateIsOld && !endDateIsOld)
case B- (!startDateIsOld && endDateIsOld)
In these both cases the current date is said to be in range .
- (BOOL)isDate:(NSDate *)date inRangeFirstDate:(NSDate *)firstDate lastDate:(NSDate *)lastDate {
BOOL startDateIsOld = false;
BOOL endDateIsOld = false;
if ([date compare:firstDate]==NSOrderedAscending) {
NSLog(#"first date is after current date");
startDateIsOld=NO;
}
if ([date compare:lastDate]==NSOrderedDescending){
NSLog(#"last date is before current date");
endDateIsOld=YES;
}
if ([date compare:firstDate]==NSOrderedDescending) {
NSLog(#"first date is before current date");
startDateIsOld=YES;
}
if ([date compare:lastDate]==NSOrderedAscending){
NSLog(#"last date is after current date");
endDateIsOld=NO;
}
if ((startDateIsOld && !endDateIsOld) || (!startDateIsOld && endDateIsOld) ) {
NSLog(#"date is in range");
return YES;
}
return NO;
}
TO simplify this method you can just do:
if ((([date compare:firstDate]==NSOrderedDescending) && ([date compare:lastDate]==NSOrderedAscending)) || (([date compare:firstDate]==NSOrderedAscending) && ([date compare:lastDate]==NSOrderedDescending))) {
NSLog(#"date is in range");
return YES;
}

Check if the given date time is between two others date time in Objective C

I am trying to figure out the way to check my date time is between two others date time, for example I am getting current time from my server as "Mar 16 2015 14:17" so I want to check that whether this date time is between two others date time range as "Feb 4 2015 08:00-09:00" or not.
I would suggest the following class method
+ (BOOL)checkDate:(NSDate*)dateToCheck startingDate:(NSDate*)startingDate endDate:(NSDate*)endDate
{
BOOL returnValue;
if ([startingDate compare:endDate]==NSOrderedDescending)
{
returnValue = [dateToCheck compare:endDate]==NSOrderedAscending && [dateToCheck compare:startingDate]==NSOrderedDescending;
}
else if ([startingDate compare:endDate]==NSOrderedAscending)
{
returnValue = [dateToCheck compare:startingDate]==NSOrderedAscending && [dateToCheck compare:endDate]==NSOrderedDescending;
}
else
{
returnValue = [dateToCheck compare:startingDate]==NSOrderedSame && [dateToCheck compare:endDate]==NSOrderedSame;
}
return returnValue;
}
Current date :
NSDate *currentDate = [NSDate date];
NSLog(#"-- %#",currentDate);
Start date :
// Start Date - 2015-03-12 00:00:58 +0000
NSString *stringStartDate = #"2015-03-12 00:00:58";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd hh:mm:ss"];
NSDate *dateStart = [formatter dateFromString:stringStartDate];
End date :
// End Date - 2015-03-20 00:00:58 +0000
NSString *stringEndDate = #"2015-03-20 00:00:58";
NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
[formatter1 setDateFormat:#"yyyy-MM-dd hh:mm:ss"];
NSDate *dateEnd = [formatter1 dateFromString:stringEndDate];
Function to check date between two date or not
BOOL isDateCheck = [self isDate:currentDate inRangeFirstDate:dateStart lastDate:dateEnd];
Function
- (BOOL)isDate:(NSDate *)date inRangeFirstDate:(NSDate *)firstDate lastDate:(NSDate *)lastDate {
return [date compare:firstDate] == NSOrderedDescending &&
[date compare:lastDate] == NSOrderedAscending;
}
Try that code if you have three NSDate instances:
NSDate *beginDate, *endDate, *checkDate;
if ([beginDate laterDate:checkDate] == checkDate &&
[checkDate laterDate:endDate] == endDate) {
//checkDate in between beginDate and endDate
}
For date parsing use the following:
NSString *inputRange = #"Feb 4 2015 08:00-09:00";
NSRange firstRange = NSMakeRange(0, inputRange.length - 6);
NSString *firstDate = [inputRange substringWithRange:firstRange];
NSDateFormatter *dateFormatter = [NSDateFormatter new];
dateFormatter.dateFormat = #"MMM dd yyyy HH:mm";
NSDate *beginDate = [dateFormatter dateFromString:firstDate];
NSString *secondDate = [inputRange substringWithRange:NSMakeRange(0, inputRange.length - 11)];
secondDate = [secondDate stringByAppendingString:[inputRange substringWithRange:NSMakeRange(inputRange.length - 5, 5)]];
NSDate *endDate = [dateFormatter dateFromString:secondDate];

Custom DatePicker using UIPIckerView

I am new to ios development. I am making a custom datepicker using uipickerview. I have datesArray to be used as a data source for uipickerview.
I want to know how to show only Labels : today,tomorrow,Fri,Sat,Sun,Mon,Tues for current week and rest dates in format "EEE, LLL d".
I tried this code but it didn't work.
for(int i=0;i<22;i++)
{
NSDate *myDate = [NSDate dateWithTimeIntervalSinceNow:60 * 60 * 24 * i];
NSDate *now=[NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateFormat:#"EEE, LLL d"];
if(myDate==now)
{
NSString *myDateString=#"today";
[datesArray addObject:myDateString];
}
else
{
NSString *myDateString = [dateFormatter stringFromDate:myDate];
[datesArray addObject:myDateString];
}
}
Try this.Hope it helps
NSString *dateFromWS = #"2013-10-16";//im taking it as static you have to take string coming from webservice
for (int i = 0; i < 22; i++)
{
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter1 setDateFormat:#"yyyy-MM-dd"];
NSDate *myDate = [NSDate dateWithTimeIntervalSinceNow:60 * 60 * 24 * i];
NSDate *now = [dateFormatter1 dateFromString:dateFromWS];
NSDate *tomorrow = [NSDate dateWithTimeInterval:60 * 60 * 24 * 1 sinceDate:now];
//NSDate *dummy = [NSDate dateWithTimeInterval:60 * 60 * 24 * 1 sinceDate:now];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateFormat:#"EEE, LLL d"];
NSString *loopDate = [dateFormatter stringFromDate:myDate];
NSString *today = [dateFormatter stringFromDate:now];
NSString *tomorrowString = [dateFormatter stringFromDate:tomorrow];
if ([loopDate isEqualToString:today]) {
[datesArray addObject:#"today"];
} else if ([loopDate isEqualToString:tomorrowString]) {
[datesArray addObject:#"tomorrow"];
} else if ((i/7) < 1) {
[datesArray addObject:[loopDate substringToIndex:3]];
} else {
[datesArray addObject:loopDate];
}
}
if(myDate==now)
is comparing 2 pointers not 2 dates. You need to use the below code
if([myDate compare:now] == NSOrderedSame)
In addition to Simon's pointer issue, your dates will include the time info and so is never likely to be identical. May be the same day but not the same time. You need to find if the day matches. I do this by:
for(int i=0;i<22;i++)
{
NSDate *myDate = [NSDate dateWithTimeIntervalSinceNow:60 * 60 * 24 * i];
NSDate *myDateNoTime = nil;
// Note: Create sysCal as a property so it is not being repeatedly recreated here
[self.sysCal rangeOfUnit:NSDayCalendarUnit startDate:&myDateNoTime interval:nil forDate:myDate];
NSDate *now=[NSDate date];
NSDate *todayDateNoTime = nil;
[self.sysCal rangeOfUnit:NSDayCalendarUnit startDate:&todayDateNoTime interval:nil forDate:now];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateFormat:#"EEE, LLL d"];
if([myDateNoTime isEqualToDate:todayDateNoTime])
{
NSString *myDateString=#"today";
[datesArray addObject:myDateString];
}
else
{
NSString *myDateString = [dateFormatter stringFromDate:myDate];
[datesArray addObject:myDateString];
}
}
Given your server date requirement and, in my opinion, a better way of handling a picker, I would put this in the datasource method instead.
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
NSString *resultString = nil;
NSDate *myDate = [self dateForRow:row];
NSDate *myDateNoTime = nil;
// Note: Create sysCal as a property so it is not being repeatedly recreated here
[self.sysCal rangeOfUnit:NSDayCalendarUnit startDate:&myDateNoTime interval:nil forDate:myDate];
NSDate *now=[NSDate date];
NSDate *todayDateNoTime = nil;
[self.sysCal rangeOfUnit:NSDayCalendarUnit startDate:&todayDateNoTime interval:nil forDate:now];
if([myDateNoTime isEqualToDate:todayDateNoTime])
{
resultString = #"Today";
} else {
// Note: using property for date formatter so I am not repeatedly creating here
resultString = [self.dayFormatter stringFromDate:myDate];
}
return resultString;
}
To determine date for the row use:
-(NSDate *)dateFromRow:(NSInteger)inRow {
NSDateComponents *daysToAdd = [[NSDateComponents alloc] init];
[daysToAdd setCalendar:self.sysCal];
NSInteger daysCalc = (-1 * (inRow -2));
[daysToAdd setDay:daysCalc];
NSDate *resultDate = nil;
NSDate *calcDate = [self.sysCal dateByAddingComponents:daysToAdd
toDate:self.myServerDate
options:0];
[self.sysCal rangeOfUnit:NSDayCalendarUnit startDate:&resultDate interval:nil forDate:calcDate];
return resultDate;
}
I suppose you are already set with the way you are doing it but I think you would find this more flexible, no limit to 21 days before or after the server date. Aircode, excuse any typos or syntax errors.
Swift 4.0
for i in 0..<22 {
var myDate = Date(timeIntervalSinceNow: 60 * 60 * 24 * i)
var now = Date()
var dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.dateFormat = "EEE, LLL d"
if myDate == now {
var myDateString = "today"
datesArray.append(myDateString)
} else {
var myDateString: String = dateFormatter.string(from: myDate)
datesArray.append(myDateString)
}
}

NSString to NSDate return null value

Here i am getting current time and check whether its in am/pm format. If its not like that, i convert 24 hour time format into 12 hour time format and add AM/PM manually.
This is my code:
- (NSString *) getCurrentTime {
NSDate *today = [NSDate date];
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setDateFormat:#"hh:mm:ss a"];
NSString *currentTime = [timeFormatter stringFromDate:today];
currentTime = [self checkTimeFormat:currentTime];
return currentTime;
}
And
- (NSString *) checkTimeFormat:(NSString *) currentTime
{
NSArray *timeArray = [currentTime componentsSeparatedByString:#":"];
int intHour = [[timeArray objectAtIndex:0] intValue];
NSString *lastVal = [timeArray objectAtIndex:2];
if ([lastVal rangeOfString:#"M"].location == NSNotFound) {
if (intHour < 12)
lastVal = [NSString stringWithFormat:#"%# AM", [timeArray objectAtIndex:2]];
else
lastVal = [NSString stringWithFormat:#"%# PM", [timeArray objectAtIndex:2]];
}
if (intHour > 12)
intHour = intHour - 12;
currentTime = [NSString stringWithFormat:#"%d:%#:%#", intHour, [timeArray objectAtIndex:1], lastVal];
NSLog(#"Current Time ==>> %#", currentTime);
return currentTime;
}
Conversion of NSString into NSDate code below:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"hh:mm:ss a"];
NSDate *testDate = [dateFormatter dateFromString:getCurrentTime];
NSLog(#"testDate => %#", testDate);
If the Time is in 12 hour format (am/pm), testDate value is getting correctly.
If the Time is in 24 hour format, testDate value is null
What is the issue?
Thanks in Advance.
You can try:
NSDate *today = [NSDate date];
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setDateFormat:#"HH:mm:ss"];
NSString *currentTime24 = [timeFormatter stringFromDate:today];
[timeFormatter setDateFormat:#"hh:mm:ss a];
NSDate *currentTime12 = [timeFormatter dateWithString:currentTime24];
NSString *currentTime = [timeFormatter stringWithDate:currentTime12];

Resources