How to get the hours,minute and am/pm from a date? [duplicate]

给你一囗甜甜゛ 提交于 2019-12-08 01:48:09

问题


I tried to extract hours,minute and am/pm from date but i am getting NULL output. I have shown below my code, please review it.

NSString *dateStr=@"29/07/2013 02:00am";
NSDateFormatter * formatter=[[NSDateFormatter alloc] init];
[formatter setDateFormat:@"hh:mmaa"];
NSDate *date=[formatter dateFromString:dateStr];
NSString *finalDate=[formatter stringFromDate:date];
NSLog(@"%@",finalDate);

Many thanks in advance


回答1:


You are very close, but you need to specify what date format your original string is in before you parse it, and then set the date format that you want the output to be in before you create it:

NSString *dateStr=@"29/07/2013 02:00am";

// Create a date formatter
NSDateFormatter * formatter=[[NSDateFormatter alloc] init];

// As rmaddy pointed out, you should set the locale:
[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];

// Set the date format for the input string
[formatter setDateFormat:@"dd/MM/yyyy hh:mma"];

// Create the NSDate from the string
NSDate *date=[formatter dateFromString:dateStr];

// Set the date format for the output string
[formatter setDateFormat:@"hh:mma"];

// Create the output string
NSString *finalDate=[formatter stringFromDate:date];
NSLog(@"%@",finalDate);  //  Output is: 02:00AM



回答2:


- (void) dateformat{
    NSDate *today = [[NSDate alloc] init];
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSGregorianCalendar];

    NSDateComponents *components = [gregorian components:NSHourCalendarUnit|NSMinuteCalendarUnit
                                                       fromDate:today];


    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setLocale:[NSLocale currentLocale]];
    [formatter setDateStyle:NSDateFormatterNoStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    NSString *dateString = [formatter stringFromDate:today];
    NSRange amRange = [dateString rangeOfString:[formatter AMSymbol]];
    NSRange pmRange = [dateString rangeOfString:[formatter PMSymbol]];
    BOOL is24hTime = (amRange.location == NSNotFound && pmRange.location == NSNotFound);

    if (is24hTime == NO ) {

        NSString *meridiem = (amRange.location == NSNotFound)?@"PM":@"AM";
        NSLog(@"%d:%d %@",components.hour,components.minute,meridiem);
    }

}


来源:https://stackoverflow.com/questions/17915586/how-to-get-the-hours-minute-and-am-pm-from-a-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!