简体   繁体   中英

Working with NSDateFormatter

Currently, I am attempting to format an NSDate string.

2013-08-25 22:54:00.500 MYSCHEDULER[23153:c07] 9:00 PM
2013-08-25 22:54:00.501 MYSCHEDULER[23153:c07] 2013-08-10 04:00:00 +0000

Here's the code I use:

- (NSString *)monthFormatter:(NSDate *)date
{
    static NSDateFormatter *dateFormat = nil;

    if (nil == dateFormat) {
        dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@"h:mm a"];
    }

    return [dateFormat stringFromDate:date];
}

What I would like to do is create a date formatter that takes out appending 0s.

So I have a time like 9:00 PM and I would like to convert the time to 9 PM . Is there a way this can be accomplished with a NSDateFormatter ?

I attempted to do this : [dateFormat setDateFormat:@"h:ma"]; but it just made the date show up like so : 9:0 PM

Anyone have any ideas?

EDIT

Also, I understand I could write:

[dateFormat setDateFormat:@"h a"];

and that would satify this case but for the case of maybe 9:30 PM , what would need to be done? Maybe a checker within the dateformatter method? But I figure Apple has already implemented this case.

您需要添加这样的内容,希望它能起作用:)

[dateFormat setDateFormat:@"MM/dd/yyyy HH"];

if you want 9 PM as your answer give a below code try it works fine as per your need

NSString *time = [self monthFormatter:[NSDate date]];
NSArray *timeAMPM = [time componentsSeparatedByString:@" "];
NSArray *hour = [time componentsSeparatedByString:@":"];

NSLog(@"the time :%@ %@",[hour objectAtIndex:0],[timeAMPM objectAtIndex:1]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM