iOS日期格式 [英] iOS Date formatting

查看:114
本文介绍了iOS日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在美国地区使用该应用程序时,我需要格式化以下日期:1月1日,7月2日,11月28日

I need to have the following date formatted while using the application with an US locale: January 1st, July 2nd, November 28th

我应该怎么做?

NSDateFormatter搜索,但是我无法设置适当的格式,并且默认格式太长.

Searched with NSDateFormatter, but I'm not able to set an appropriate format and default formats are too long.

推荐答案

NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"MMMM dd'st'"];

NSDate *now = [[NSDate alloc] init];

NSString *dateString = [format stringFromDate:now];
NSLog(@"%@",dateString);

这将为您提供所需的格式,但是您需要添加一些条件以添加适当的'st','nd','rd'等. 像这样

this will give you the required format but you need to add some condition to add proper 'st','nd','rd' etc. like this

这可能对您有帮助

NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"MMMM dd"];

NSDate *now = [[NSDate alloc] init];

NSString *dateString = [format stringFromDate:[now dateByAddingTimeInterval:(-60*60*24*10)]];
NSMutableString *tempDate = [[NSMutableString alloc]initWithString:dateString];
int day = [[tempDate substringFromIndex:[tempDate length]-2] intValue];
switch (day) {
    case 1:
    **case 21:
    case 31:**
        [tempDate appendString:@"st"];
        break;
    case 2:
    **case 22:**
        [tempDate appendString:@"nd"];
        break;
    case 3:
    **case 23:**
        [tempDate appendString:@"rd"];
        break;
    default:
        [tempDate appendString:@"th"];
        break;
}
NSLog(@"%@",tempDate);

这篇关于iOS日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆