How to get the time in am/pm format iphone NSDateFormatter?

后端 未结 8 1100
一生所求
一生所求 2020-12-13 05:44

Am working in an iPhone app with using the NSDateFormatter. Am getting the time from the webservice like \"00:00:00\", \"16:00:00\",\"15:30:00\" and so on. I ne

相关标签:
8条回答
  • 2020-12-13 06:16

    Try HH:mm:ss (notice the capitals in the hour format)

    0 讨论(0)
  • You can use the .ShortStyle which will adapt to the current locale:

    let timeFormatter = NSDateFormatter()
    timeFormatter.dateStyle = .NoStyle
    timeFormatter.timeStyle = .ShortStyle
    timeFormatter.stringFromDate(NSDate())
    

    Which returns 17:12 or 5:12 PM depending on the current device locale.

    0 讨论(0)
  • 2020-12-13 06:27

    Why are you again allocating the NSDateFormatter ?

    you Just need to format it to NSDate and then again to NSString,

        NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
        [dateFormatter setDateFormat:@"HH:mm:ss"];
    
        NSDate *date = [dateFormatter dateFromString:dats1];
    
        [dateFormatter setDateFormat:@"hh:mm a"];
    
        NSString *formattedDate = [dateFormatter stringFromDate:date];
    
        NSLog(@"%@",formattedDate);
    
    0 讨论(0)
  • 2020-12-13 06:28

    your date format should be:

      [dateFormatter3 setDateFormat:@"HH:mm:ss"]; 
    

    check the Date Format Pattern Doku

    0 讨论(0)
  • 2020-12-13 06:29

    Swift 5:

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "hh mm a"
    let formattedDate = dateFormatter.string(from: Date())
    
    0 讨论(0)
  • 2020-12-13 06:32

    If your time format is in 24hrs please use "HH:mm:ss" format. Please test the code and let me know if it is working for you. I have tested and it is returning "4 PM"

    NSString *dats1 = @"16:00:00";
     NSDateFormatter *dateFormatter3 = [[[NSDateFormatter alloc] init] autorelease];
     [dateFormatter3 setDateStyle:NSDateFormatterMediumStyle];  
     [dateFormatter3 setDateFormat:@"HH:mm:ss"]; 
     NSDate *date1 = [dateFormatter3 dateFromString:dats1];
     NSLog(@"date1 : %@", date1); **// Here returning (null)**
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
     [formatter setDateFormat:@"hh:mm a"];
     NSLog(@"Current Date: %@", [formatter stringFromDate:date1]); **// Here also returning (null)**
     [formatter release];
    

    Thanks.

    0 讨论(0)
提交回复
热议问题