-1

time is string format like 10:27:43. but when i convert in to date format. it is going to change Sat Jan 1 10:27:43 2000.but i need only time like 10:27:43

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEE MMM dd HH:mm:ss ZZZ yyyy"];

 NSLog(@"Date is %@", dateTime);

// Convert to new Date Format
[dateFormatter setDateFormat:@"HH:mm:ss"];
newDate = [dateFormatter stringFromDate:dateTime];

 NSLog(@" string Date is %@", newDate);

 NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init] ;
[dateFormatter1 setDateFormat:@"HH:mm:ss"];

 //[dateFormatter1 setDateFormat:@"dd/mm/yyyy"];
NSDate *dateFromString = [dateFormatter1 dateFromString:newDate];

NSLog(@"date format date %@",dateFromString);
ishant
  • 1
  • 3

3 Answers3

0

you need to convert dateFormat as per date is coming and after convert it as you want.

Try this below code..

NSString *dateTime = @"Thu Jan 25 10:38:11 2018";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"EEE MMM dd HH:mm:ss yyyy"];
    NSDate *dateFromString = [dateFormatter dateFromString:dateTime];
    NSLog(@"Date is %@", dateTime);
    // Convert to new Date Format
    [dateFormatter setDateFormat:@"HH:mm:ss"];
    NSString *result = [dateFormatter stringFromDate:dateFromString];
    NSLog(@"result %@",result);
Nirav Kotecha
  • 2,493
  • 1
  • 12
  • 26
0

Split the time in date components and use that components as a time.

Check below code.

NSString *aStrTime = @"10:27:43";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm:ss"];
NSDate *date = [dateFormatter dateFromString:aStrTime];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:date];
NSInteger hour = [components hour];
NSInteger minute = [components minute];
NSInteger sec = [components second];

NSLog(@"%d:%d:%d", hour, minute, sec);

Note: change aStrTime and dateFormatPattern according to your need.

dahiya_boy
  • 9,298
  • 1
  • 30
  • 51
0
You can try the following code:-

For e.g:- if you are getting the date in 10-02-2017 12:30:50 format

NSString *strDate = @"10-02-2017 12:30:50";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
[dateFormat setDateFormat:@"dd-mm-yyyy HH:mm:ss"];
NSDate *date = [dateFormatter dateFromString:strDate];
NSLog(@"The Date is: %@", date);

// By this code you will get the date in NSDate form. Now you can change the format to get the time

[dateFormat setDateFormat:@"HH:mm:ss"];
NSString *strFinalTime = [dateFormatter stringFromDate:strDate];
NSLog(@"strFinalTime: %@",strFinalTime);
Swati Gautam
  • 191
  • 9