I am trying to parse a clock string composed by a multiple number of minutes and convert it to a NSDate using a NSDateFormatter.
An example of the string I am trying to parse is #"1234:56", where 1234 are the minutes of the clock and 56 the seconds. I tried to use a format such as #"mmmm:ss" but it returned nil.
In case it is possible, can anyone help me with this?
Thanks
I'm not sure about the thing that you want to do, but I suggest do something like that:
NSArray *timeArray = [#"1234:56" componentsSeparatedByString:#":"];
NSUInteger minutes = [[timeArray firstObject] integerValue];
NSUInteger seconds = [[timeArray lastObject] integerValue];
NSTimeInterval totalSeconds = minutes*60+seconds;
And then you should create a new date object and work with this.
NSDate *newDate = [NSDate dateWithTimeIntervalSince1970:totalSeconds];
NSDateFormatter only works with legal date format and there is no 'mmmm'.You should get date by yourself:
NSString *str = #"234:56";
NSArray<NSString *> *components = [str componentsSeparatedByString:#":"];
NSInteger minute = 0;
NSInteger second = 0;
switch (components.count) {
case 1:
second = components[0].integerValue;
break;
case 2:
second = components[0].integerValue;
minute = components[1].integerValue;
break;
default:
break;
}
// then convert to hours.
Try this.
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm:ss.SSS"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *timeString=[dateFormatter stringFromDate:timerDate];
self.timerLabel.text = timeString;
If you want to convert that to HH:mm:ss then my approach will be something like:
// assuming you wouldn't have any hours in the string and format will always be minutes:seconds
NSArray *timeArray = [#"1234:56" componentsSeparatedByString:#":"];
//array's firstObject will be the "minutes/Hours"
NSString *minutesAndHours = [timeArray firstObject];
int hours = [minutesAndHours intValue]/60;
int minutes = [minutesAndHours intValue]%60;
int seconds = [timeArray lastObject];
//create the format
NSString *time = [NSString stringWithFormat:#"%d:%d:%d",hours,minutes,seconds];
//then use the time format
NSString *time = [NSString stringWithFormat:#"%d:%d:%d",hours,minutes,seconds];
NSDateFormatter *format = [NSDateFormatter new];
[format setDateFormat:#"HH:mm:ss"];
NSDate *date = [format dateFromString:time];
something like this
Related
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);
I am having a mutable array in that array i am having only past date, current date & future date. I have to separate the future date & store into another array. Can you help me.
This is my array:
uniqueItems(
"2015-03-01",
"2015-02-28",
"2015-02-22",
"2015-02-21",
"2015-02-20",
"2015-02-15",
"2015-02-14",
"2015-02-13",
"2015-02-08",
"2015-02-07",
"2015-02-01",
"2015-01-31",
"2015-01-30",
"2015-01-25",
"2015-01-24",
"2015-01-18",
"2015-01-17",
"2015-01-16",
"2015-01-11",
"2015-01-10",
"2014-12-07"
I have tried this coding, but is not working.
NSDate *currentDate = [NSDate date];
NSDate* dateAdded=(NSDate*)[uniqueItems objectAtIndex:0];
double min = [currentDate timeIntervalSinceDate:dateAdded];
int minIndex = 0;
for (int i = 1; i < [uniqueItems count]; ++i)
{
double currentmin = [currentDate timeIntervalSinceDate:[uniqueItems objectAtIndex:i]];
if (currentmin < min) {
min = currentmin;
minIndex = i;}}
you can use NSPredicate block for that. your array does not contain NSDate objects so we need to convert it into NSDate and then compare with [NSDate date]
NSPredicate *findFutureDates = [NSPredicate predicateWithBlock: ^BOOL(id obj, NSDictionary *bind){
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:#"yyyy-MM-dd"];
[df setTimeZone:[NSTimeZone systemTimeZone]];
NSDate *dd = [df dateFromString:(NSString *)obj ];
return ([[NSDate date] compare:dd] == NSOrderedAscending);
}];
NSArray *arrFutureDates = [yourArray filteredArrayUsingPredicate: findFutureDates];
NSLog(#"%#",arrFutureDates);
if you pass NSOrderedAscending will give you future dates if you pass NSOrderedDescending will give you past dates.
NSDate *currentDate = [NSDate date];
NSDate *date;
int offset = 0;
NSMutableArray *futureArray = [[NSMutableArray alloc] init];
for (int i = 1; i < [uniqueItems count]; ++i)
{
date = [uniqueItems objectAtIndex:i];//TODO: Convert to NSDate
offset = [currentDate timeIntervalSinceDate:date];
if (offset < 0) {
[futureArray addObject:[uniqueItems objectAtIndex:i]];
}
}
This is a idea. Sorry, I'm coding in notepad without test.
Your array is of string format not an NSDate object. You can convert a string to nsdate
NSString *dateString = #"2010-02-13";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
and then you could do your check.
I need to get a NSString that displays a total of traveled time using 2 NSStrings
I have
NSString *origin = [NSString stringWithFormat:#"5:30"];
NSString *destiny = [NSString stringWithFormat:#"6:00"];
The problem is I don't know how to format this NSStrings to NSDate and do destiny - origin so the output would be a new NSString that says 30 minutes
EDIT: I've just investigate a little about the NSDateFormatter but if I use it:
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm"];
NSDate * mydate = [dateFormatter dateFromString:origin];
NSDate returns me a nil Is there something wrong?
Any help will be very appreciated.
NSString *origin = #"5:30";
NSString *destiny = #"6:00";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"H:mm"];
NSDate *originDate = [dateFormatter dateFromString:origin];
NSDate *destinyDate = [dateFormatter dateFromString:destiny];
NSTimeInterval interval = [destinyDate timeIntervalSinceDate:originDate];
NSDate *intervalDate = [NSDate dateWithTimeInterval:interval sinceDate:originDate ];
NSDateComponents *comps =[[NSCalendar currentCalendar] components:NSMinuteCalendarUnit
fromDate:originDate
toDate:intervalDate
options:0];
Now the NSDateComponents will hold the difference in minutes
NSLog(#"%ld", [comps minute]);
will log 30
If you would like the hours and minutes, you can do
NSString *origin = #"5:30";
NSString *destiny = #"7:00";
// ....
NSDateComponents *comps =[[NSCalendar currentCalendar] components: (NSMinuteCalendarUnit|NSHourCalendarUnit)
fromDate:originDate
toDate:intervalDate
options:0];
Now comps will hold the 90 minutes as 1 hour and 30 minutes.
NSLog(#"%ld %ld", [comps hour],[comps minute]);
logs 1 30
NSString *origin = #"5:30";
NSString *destiny = #"6:00";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"H:mm"];
NSDate *originDate = [dateFormatter dateFromString:origin];
NSDate *destinyDate = [dateFormatter dateFromString:destiny];
NSTimeInterval diffInSeconds = [destinyDate timeIntervalSinceDate:originDate];
NSTimeInterval diffInMinutes = diffInSeconds / 60;
NSString *minutesString = [NSString stringWithFormat:#"%0.0f", diffInMinutes];
This question already has answers here:
Can't convert from NSString to NSDate
(2 answers)
Closed 9 years ago.
I'm trying to convert a NSString into seconds, but i'm doing something wrong. This is my code:
The text in _myTextField, come from a uidatepicker in the format of HH:mm.
NSString *teste = [[NSString alloc]init];
teste = [_myTextField text];
NSDateFormatter *formatarteste = [[NSDateFormatter alloc]init];
[formatarteste setDateFormat:#"s"];
NSDate *dateFromString = [[NSDate alloc]init];
dateFromString = [formatarteste dateFromString:teste];
NSLog(#"%#", dateFromString);
i Always get i null result on the nslog. I tried to convert the dateFromString, back to a string before using NSLog, but still got a null message.
As requested here is more of the code i using:
I have a textfield that calls a uidatepicker, that is load on super viewdidload:
[_myTextField setText:#"03:00"];
UIDatePicker *datepicker = [[UIDatePicker alloc]init];
//[datepicker setDate:[NSDate date]];
[datepicker setDatePickerMode:UIDatePickerModeTime];
[datepicker addTarget:self action:#selector(updateTextField:) forControlEvents:UIControlEventValueChanged];
[self.myTextField setInputView:datepicker];
And this is the updateTextfield function:
UIDatePicker *picker = (UIDatePicker*)self.myTextField.inputView;
NSDateFormatter *formatar = [[NSDateFormatter alloc]init];
[formatar setDateFormat:#"HH:mm"];
NSString *textoDoField = [formatar stringFromDate:picker.date];
self.myTextField.text = [NSString stringWithFormat:#"%#", textoDoField];
One way (not necessarily the simplest) to calculate seconds since midnight from the time;
// NSString *teste = #"14:52";
NSDateFormatter *formatarteste = [[NSDateFormatter alloc]init];
[formatarteste setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
[formatarteste setDateFormat:#"HH:mm"];
NSDate *dateFromString = [formatarteste dateFromString:teste];
NSTimeInterval interval =
[dateFromString timeIntervalSinceDate:
[NSDate dateWithString: #"2000-01-01 00:00:00 +0000"]];
NSLog(#"%f", interval);
// >>> 53520
...or the somewhat more straight forward;
// NSString *teste = #"14:52";
int h,m;
const char *bytes = [teste UTF8String];
sscanf(bytes, "%d:%d", &h,&m);
int seconds = h*3600+m*60;
NSLog(#"%d", seconds);
// >>> 53520
Guys i was looking at this at wrong way, i did not need to transform the NSString into a NSDate.
I just need to get the NSString like 03:00, separate the "hours" from the "minutes", then, i multiple the hours x 3600 and the minutes x 60, to get the seconds in 3 hours for example.
The whole point of this was to create a Notification that run in a determinate time, using the [NSDate dateWithTimeIntervalSinceNow: NUMBER OF SECONDS FOR THE NOTIFICATION APPEAR];
And thats it!
This is the code i using to get the Seconds, from the textfield string:
NSArray *arrayWithNumberValue = [teste componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#":"]];
NSInteger valorHoras = [arrayWithNumberValue[0] intValue];
NSInteger valorMin = [arrayWithNumberValue[1] intValue];
NSInteger horasEmSegundos = valorHoras * 3600;
NSInteger minEmSegundos = valorMin * 60;
NSInteger proximoAlarme = horasEmSegundos + minEmSegundos;
manualTimer *horamanual = [[manualTimer alloc]init];
[horamanual tempoAlerta:&proximoAlarme];
NSLog(#"%ld", (long)proximoAlarme);
I have array which is like as below
_combinedBirthdates(
"03/12/2013",
"03/12/2013",
"08/13/1990",
"12/09/1989",
"02/06",
"09/08",
"03/02/1990",
"08/22/1989",
"03/02",
"05/13",
"10/16",
"07/08",
"08/31/1990",
"04/14/1992",
"12/15/1905",
"08/14/1989",
"10/07/1987",
"07/25",
"07/17/1989",
"03/24/1987",
"07/28/1988",
"01/21/1990",
"10/13"
)
all elements are NSString in above NSArray.
How can I make another array which contains number of days remain for particular date
something like this
_newlymadeArray(
"125",
"200",
"50",
"500",
"125",
and so on
)
Use this algorithm:
Obtain the current year
Convert each date from your array to a date in the current year. For example, "03/02/1990" becomes "03/02/2013"
If the date from the step 2 is before the current date, advance its year by one (i.e. "03/02/2013" becomes "03/02/2014")
Using a technique from this question, find the number of days till the date from step 3. It will be less than the number of days in a year.
unsigned int unitFlags = NSDayCalendarUnit;
NSCalendar *currCalendar = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
NSMutableArray * _newlymadeArray = [[NSMutableArray alloc] init];
for (NSString * str in _combinedBirthdates){
NSDate * toDate = [dateFormatter dateFromString:str];
NSDateComponents *daysInfo = [currCalendar components:unitFlags fromDate:[NSDate date] toDate:toDate options:0];
int days = [daysInfo day];
[_newlymadeArray addObject:[NSString stringWithFormat:#"%d",days]];
}
You need to iterate through the first array and get the date in NSDate and use the info to get the difference in days from the current date to the next date in the array.
You will have to add the necessary checks and this is untested code.
Try this code snap.
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setTimeZone:[NSTimeZone localTimeZone]];
[formatter setDateFormat:#"MM/dd/yyyy"];
NSDate *currentDate = [formatter dateFromString:#"03/12/2013"];
NSTimeInterval srcInterval = [currentDate timeIntervalSince1970];
NSArray *_combinedBirthdates = #[#"03/15/2013", #"05/15/2013"];
NSMutableArray *_newlymadeArray = [NSMutableArray array];
const NSInteger SECONDS_PER_DAY = 60 * 60 * 24;
for (NSString *one in _combinedBirthdates) {
NSDate *destDate = [formatter dateFromString:one];
NSTimeInterval destInterval = [destDate timeIntervalSince1970];
NSInteger diff = (destInterval - srcInterval) / SECONDS_PER_DAY;
[_newlymadeArray addObject:[NSString stringWithFormat:#"%d", diff]];
}
That's it! :)