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);
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 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
I'm using AVPlayer. And I want to get current time of player to show for user.
The problem is the string getting wrong value from NSDate you can see in images
This is date value
And this string value getting from date
please help to solve. this is my code
NSDate* d = [NSDate dateWithTimeIntervalSince1970:CMTimeGetSeconds(mPlayer.currentTime)];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
[dateFormatter setDateFormat:#"mm:ss"];
NSString* result = [dateFormatter stringFromDate:d];
avPlayerLabel.text = result;
You don't even need an NSDateFormatter:
Float64 time = CMTimeGetSeconds(mPlayer.currentTime) + 0.5;
unsigned minutes = (unsigned)time / 60;
unsigned seconds = (unsigned)time % 60;
avPlayerLabel.text = [NSString stringWithFormat:#"%02u:%02u", minutes, seconds];
After adding a comment i need to show comment timing like year ago,day ago,minutes ago and second ago on label but it returns -4425,-33434 seconds ago "random numbers".
Here is my code shown below am using in my app.
NSString *inDateStr = [NSString stringWithFormat:#"%#",[[[dict objectForKey:#"d"] objectAtIndex:indexPath.row-1] objectForKey:#"created"]];
NSString *s = #"yyyy-MM-dd HH:mm:ss";
// about input date(GMT)
NSDateFormatter *inDateFormatter = [[NSDateFormatter alloc] init];
inDateFormatter.dateFormat = s;
inDateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT-7.00"];
NSDate *inDate = [inDateFormatter dateFromString:inDateStr];
// about output date(IST)
NSDateFormatter *outDateFormatter = [[NSDateFormatter alloc] init];
outDateFormatter.timeZone = [NSTimeZone localTimeZone];
outDateFormatter.dateFormat = s;
NSString *outDateStr = [outDateFormatter stringFromDate:inDate];
// final output
NSLog(#"[in]%# -> [out]%#", inDateStr, outDateStr);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *dateStartingString = [[NSDate alloc] init];
NSString *datestartString = outDateStr;
dateStartingString = [dateFormatter dateFromString:datestartString];
NSTimeInterval timeDifference = [[NSDate date] timeIntervalSinceDate:dateStartingString];
double minutes = timeDifference / 60;
double hours = minutes / 60;
double seconds = timeDifference;
double days = minutes / 1440;
UILabel * dateLbl=[[UILabel alloc] initWithFrame:CGRectMake(155, [[CountArr objectAtIndex:indexPath.row] floatValue]-1, 80, 20)];
if(seconds>=86400)
dateLbl.text=[NSString stringWithFormat:#"%.0f days ", days];
else if(seconds>=3600 && seconds<86400 )
dateLbl.text=[NSString stringWithFormat:#"%.0f hours ", hours];
else if (seconds>=60 && seconds<3600 )
dateLbl.text=[NSString stringWithFormat:#"%.0f minutes ", minutes];
else
dateLbl.text=[NSString stringWithFormat:#"%.0f seconds ", seconds];
dateLbl.textColor=[UIColor lightGrayColor];
dateLbl.font = [UIFont systemFontOfSize:12];
[cell.contentView addSubview:dateLbl];
I believe NSDateFormatter only takes a string and returns a NSDate object. Setting the timezone is meant for setting the property of NSDate, but doesn't actually convert the time provided. So in the end if you put in 5:30 GMT, you will get 5:30 IST.
You would instead want to use NSCalender to do timezone conversions.
You can use this method to get difference in date.
Make sure that date formate is correct. If you are getting negative value just check date format.
-(NSDateComponents *)getDateDifference:(NSString *)date
{
NSDate *dateA=[NSDate date]; //Current date
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *dateB = [dateFormatter dateFromString:date];//Convert nsstring to nsdate
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; //Gregorian allocation
NSDateComponents *components = [calendar components:NSDayCalendarUnit|NSHourCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit
fromDate:dateA
toDate:dateB
options:0]; //Get day and hour
return components;
}
// Call method like
NSDateComponents *difference = [self getDateDifference:marriageDate];
NSLog(#"diff year = %f",difference.year);
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! :)