6

I have 2:01:20 PM format in one label; after some calculations, I need to change the hour and/or minute of that label.

That is ,Is it possible to change that label value, by converting it as NSDate object and modifying hour and minute like 3:20:30 PM?

Are there any setter methods for this?

Cœur
  • 37,241
  • 25
  • 195
  • 267
mac
  • 4,760
  • 7
  • 31
  • 33
  • if i use [string1 replaceCharactersInRange: NSMakeRange(0,5) withString:[NSString stringWithFormat:@"%d:0%d",hour,finalMinute] i need to check lot of conditions that if minute is less than 10 append string as 01,02,03 .... and if hour is greater than 9 i need to change range , because of 12:03:23 PM ..... – mac Jun 04 '10 at 12:35

2 Answers2

27

The answer to your first question "how to set hour minute in nsdate programatically?" is following:

    NSDate* result;
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setMinute:0];
    [comps setHour:0];
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    result = [gregorian dateFromComponents:comps];
    [comps release];
BamboOS
  • 478
  • 5
  • 13
  • It picks the date as "0001-01-01". How to set current date? – Satyam Mar 04 '15 at 16:34
  • 1
    This is how you can set current date in components: `NSDateComponents *components = [calendar components: NSCalendarUnitYear| NSCalendarUnitMonth| NSCalendarUnitDay fromDate:[NSDate date]];` – iBug Sep 08 '15 at 06:16
1

If you need to calculate specific real instances in time e.g. 3:20:30 PM Oct 23, 2010, then you want to use NSCalendar which lets you decompose dates and do date related calculations.

Word of warning. Date and time calculations are surprisingly complex and detailed. Expect to spend a couple of hours learning the API.

TechZen
  • 64,370
  • 15
  • 118
  • 145
  • my code is NSDateFormatter *timeFormatter = [[[NSDateFormatter alloc] init] autorelease]; [timeFormatter setDateStyle:NSDateFormatterNoStyle]; [timeFormatter setTimeStyle:NSDateFormatterMediumStyle]; NSDate *stringTime = [NSDate date]; NSString *formattedDateStringTime = [timeFormatter stringFromDate:stringTime]; //NSLog(@"the time string is %@",formattedDateStringTime); time.text = formattedDateStringTime; here , my problem is i need to change the time hour, minute, so, if i follow above comment its too hard, any other classes to make it easy TechZen. Thanks For quick answer. – mac Jun 04 '10 at 12:45