iOS Objective-C NSDateFormatter的一些使用参考

NSDateFormatter对象的作用,就是把NSDate对象转换为字符串,以及将字符串转换成NSDate

1. 利用NSDateFormatterStyle枚举值将NSDate对象转换为字符串

NSDate对象表示的是一个时间,包括了日期,也包括了时分秒。所以NSDateFormatter也有两个方法,分别用来表示时间的日期和时分秒。

1.1 表示日期的方法

NSDateFormattersetDateStyle:方法,用来设置日期的表示法。

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterFullStyle];

NSDate *currentDate = [NSDate date];
NSString *dateString = [dateFormatter stringFromDate:currentDate];

NSLog(@"current date string: %@", dateString); // 2017年8月3日 星期四

代码中的NSDateFormatterFullStyleNSDateFormatterStyle枚举值,一共五个。它们所能表现的形式如下:

[dateFormatter setDateStyle:NSDateFormatterNoStyle]; // 不产生任何效果
[dateFormatter setDateStyle:NSDateFormatterShortStyle]; // 2017/8/3
[dateFormatter setDateStyle:NSDateFormatterMediumStyle]; // 2017年8月3日
[dateFormatter setDateStyle:NSDateFormatterLongStyle]; // 2017年8月3日
[dateFormatter setDateStyle:NSDateFormatterFullStyle]; // 2017年8月3日 星期四

1.2 表示时分秒的方法

NSDateFormattersetTimeStyle:方法,用来设置时分秒的表示法。

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterFullStyle];

NSDate *currentDate = [NSDate date];
NSString *dateString = [dateFormatter stringFromDate:currentDate];

NSLog(@"current date string: %@", dateString); // 中国标准时间 下午2:53:42  

使用和上面一样的NSDateFormatterStyle枚举值。它们在时分秒上的表现如下:

[dateFormatter setTimeStyle:NSDateFormatterNoStyle]; // 不产生任何效果
[dateFormatter setTimeStyle:NSDateFormatterShortStyle]; // 下午2:51
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle]; // 下午2:52:25
[dateFormatter setTimeStyle:NSDateFormatterLongStyle]; // GMT+8 下午2:52:25
[dateFormatter setTimeStyle:NSDateFormatterFullStyle]; // 中国标准时间 下午2:53:42

2. 利用格式字符串将NSDate对象转换成字符串

使用格式字符串,就要使用NSDateFormattersetDateFormat:方法。

NSDateFormatter *dateStringFormatter = [[NSDateFormatter alloc] init];
[dateStringFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSDate *currentDate = [NSDate date];
NSLog(@"date string: %@", [dateStringFormatter stringFromDate:currentDate]); // 2017-08-03 16:13:03

格式字符串的格式是使用Unicode Technical Standard #35标准。下面是对常用格式的列举(注释部分就是结果字符串的样例):

[dateStringFormatter setDateFormat:@"y"]; // 2017
[dateStringFormatter setDateFormat:@"yy"]; // 17
[dateStringFormatter setDateFormat:@"yyy"]; // 2017
[dateStringFormatter setDateFormat:@"yyyy"]; // 2017

[dateStringFormatter setDateFormat:@"M"]; // 8
[dateStringFormatter setDateFormat:@"MM"]; // 08
[dateStringFormatter setDateFormat:@"MMM"]; // 8月
[dateStringFormatter setDateFormat:@"MMMM"]; // 八月

[dateStringFormatter setDateFormat:@"d"]; // 3
[dateStringFormatter setDateFormat:@"dd"]; // 03
[dateStringFormatter setDateFormat:@"D"]; // 215,一年中的第几天

[dateStringFormatter setDateFormat:@"h"]; // 4
[dateStringFormatter setDateFormat:@"hh"]; // 04
[dateStringFormatter setDateFormat:@"H"]; // 16 24小时制
[dateStringFormatter setDateFormat:@"HH"]; // 16

[dateStringFormatter setDateFormat:@"m"]; // 28
[dateStringFormatter setDateFormat:@"mm"]; // 28
[dateStringFormatter setDateFormat:@"s"]; // 57
[dateStringFormatter setDateFormat:@"ss"]; // 04

[dateStringFormatter setDateFormat:@"E"]; // 周四
[dateStringFormatter setDateFormat:@"EEEE"]; // 星期四
[dateStringFormatter setDateFormat:@"EEEEE"]; // 四
[dateStringFormatter setDateFormat:@"e"]; // 5 (显示的是一周的第几天(weekday),1为周日。)
[dateStringFormatter setDateFormat:@"ee"]; // 05
[dateStringFormatter setDateFormat:@"eee"]; // 周四
[dateStringFormatter setDateFormat:@"eeee"]; // 星期四
[dateStringFormatter setDateFormat:@"eeeee"]; // 四

[dateStringFormatter setDateFormat:@"z"]; // GMT+8
[dateStringFormatter setDateFormat:@"zzzz"]; // 中国标准时间

[dateStringFormatter setDateFormat:@"ah"]; // 下午5
[dateStringFormatter setDateFormat:@"aH"]; // 下午17
[dateStringFormatter setDateFormat:@"am"]; // 下午53
[dateStringFormatter setDateFormat:@"as"]; // 下午52

常用参数

参数说明
aAM/PM (上午/下午)
A0~86399999 (一天的第A微秒)
c/cc1~7 (一周的第一天, 周天为1)
cccSun/Mon/Tue/Wed/Thu/Fri/Sat (星期几简写)
ccccSunday/Monday/Tuesday/Wednesday/Thursday/Friday/Saturday (星期几全拼)
d1~31 (月份的第几天, 带0)
D1~366 (年份的第几天,带0)
e1~7 (一周的第几天, 带0)
E~EEESun/Mon/Tue/Wed/Thu/Fri/Sat (星期几简写)
EEEESunday/Monday/Tuesday/Wednesday/Thursday/Friday/Saturday (星期几全拼)
F1~5 (每月的第几周, 一周的第一天为周一)
gJulian Day Number (number of days since 4713 BC January 1) 未知
G~GGGBC/AD (Era Designator Abbreviated) 未知
GGGGBefore Christ/Anno Domini 未知
h1~12 (0 padded Hour (12hr)) 带0的时, 12小时制
H0~23 (0 padded Hour (24hr)) 带0的时, 24小时制
k1~24 (0 padded Hour (24hr) 带0的时, 24小时制
K0~11 (0 padded Hour (12hr)) 带0的时, 12小时制
L/LL1~12 (0 padded Month) 第几月
LLLJan/Feb/Mar/Apr/May/Jun/Jul/Aug/Sep/Oct/Nov/Dec 月份简写
LLLLJanuary/February/March/April/May/June/July/August/September/October/November/December 月份全称
m0~59 (0 padded Minute) 分钟
M/MM1~12 (0 padded Month) 第几月
MMMJan/Feb/Mar/Apr/May/Jun/Jul/Aug/Sep/Oct/Nov/Dec
MMMMJanuary/February/March/April/May/June/July/August/September/October/November/December
q/qq1~4 (0 padded Quarter) 第几季度
qqqQ1/Q2/Q3/Q4 季度简写
qqqq1st quarter/2nd quarter/3rd quarter/4th quarter 季度全拼
Q/QQ1~4 (0 padded Quarter) 同小写
QQQQ1/Q2/Q3/Q4 同小写
QQQQ1st quarter/2nd quarter/3rd quarter/4th quarter 同小写
s0~59 (0 padded Second) 秒数
S(rounded Sub-Second) 未知
u(0 padded Year) 未知
v~vvv(General GMT Timezone Abbreviation) 常规GMT时区的编写
vvvv(General GMT Timezone Name) 常规GMT时区的名称
w1~53 (0 padded Week of Year, 1st day of week = Sunday, NB: 1st week of year starts from the last Sunday of last year) 一年的第几周, 一周的开始为周日,第一周从去年的最后一个周日起算
W1~5 (0 padded Week of Month, 1st day of week = Sunday) 一个月的第几周
y/yyyy(Full Year) 完整的年份
yy/yyy(2 Digits Year) 2个数字的年份
Y/YYYY(Full Year, starting from the Sunday of the 1st week of year) 这个年份未知干嘛用的
YY/YYY(2 Digits Year, starting from the Sunday of the 1st week of year) 这个年份未知干嘛用的
z~zzz(Specific GMT Timezone Abbreviation) 指定GMT时区的编写
zzzz(Specific GMT Timezone Name) Z: +0000 (RFC 822 Timezone) 指定GMT时区的名称

3. 利用格式字符串和区域标识(NSLocale)符来自定义格式字符串

不同的国家或地区有着不同的显示时间的习惯。使用NSDateFormatterdateFormatFromTemplate:options:locale:方法可以自定义一个格式字符串出来。

NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
NSString *formatString = [NSDateFormatter dateFormatFromTemplate:@"EEEEMMMyyyyddahmmss" options:0 locale:locale];

NSDateFormatter *localeDateFormatter = [[NSDateFormatter alloc] init];
[localeDateFormatter setDateFormat:formatString];

NSString *localeTemplateString = [localeDateFormatter stringFromDate:currentDate];
// 2017年8月03日 星期四 下午9:00:09
NSLog(@"locale & template date: %@", localeTemplateString); 

@"zh_CN"是区域标识符。常用的还有@"en_US"@"en_GB".更多的标识符可以参考这里

上述代码中的Template字符串改成@"yyyyMMMddahmmssEEEE",其最后的结果字符串还是一样的。这说明字符串的本身顺序不重要。当然,你不能写成“yMyyEdsEEyE”这样的形式。

4. 将字符串转换为NSDate对象

使用NSDateFormatterdateFromString:方法来完成这个转换。这种转换的关键在于,你需要知道,被转换的字符串所表示的日期是以哪个区域的哪种格式呈现的。比如下面这个例子中,要被转换的字符串说表示的日期是,@“en_US_POSIX”区域(它比@“en_US”更加特值美国),@“yyyy-MM-dd HH:mm:ss”的格式。这些都是符合RFC3339标准。

NSDateFormatter *rfc3339DateFormatter = [[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];

[rfc3339DateFormatter setLocale:enUSPOSIXLocale];
[rfc3339DateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

[rfc3339DateFormatter setTimeZone:[NSTimeZone localTimeZone]];

// 借用前面的NSDateFormatter对象和NSDate对象
[dateStringFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *rfc3339String = [dateStringFormatter stringFromDate:currentDate];
NSDate *date = [rfc3339DateFormatter dateFromString:rfc3339String];

NSString *userVisibleDateTimeString;

if (date != nil) {
    NSDateFormatter *userVisibleDateFormatter = [[NSDateFormatter alloc] init];

    [userVisibleDateFormatter setDateStyle:NSDateFormatterShortStyle];
    [userVisibleDateFormatter setTimeStyle:NSDateFormatterShortStyle];

    userVisibleDateTimeString = [userVisibleDateFormatter stringFromDate:date];
}

// 2017/8/4 下午3:05 (所处时区不同,最终显示的时间结果也会不同。)
NSLog(@"user visible date time string: %@", userVisibleDateTimeString);

这里的关键是,dateFromString:的字符串参数和setDateFormat:的字符串参数的格式要匹配。

NSDateFormatter的常用功能介绍完毕。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是用Objective-C纯代码实现的签到日期界面。实现的界面包括一个导航栏、一个显示当前日期的标签和一个签到按钮。 ViewController.h文件: ```objective-c #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end ``` ViewController.m文件: ```objective-c #import "ViewController.h" @interface ViewController () @property (nonatomic, strong) UILabel *dateLabel; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. // 设置导航栏标题 self.navigationItem.title = @"签到"; // 设置背景颜色 self.view.backgroundColor = [UIColor whiteColor]; // 创建并添加日期标签 self.dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 50)]; self.dateLabel.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/2 - 50); self.dateLabel.textAlignment = NSTextAlignmentCenter; self.dateLabel.textColor = [UIColor blackColor]; [self.view addSubview:self.dateLabel]; // 更新日期标签的文本 [self updateDateLabel]; // 创建并添加签到按钮 UIButton *checkInButton = [UIButton buttonWithType:UIButtonTypeSystem]; checkInButton.frame = CGRectMake(0, 0, 200, 50); checkInButton.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/2 + 50); [checkInButton setTitle:@"签到" forState:UIControlStateNormal]; [checkInButton addTarget:self action:@selector(checkInButtonClicked:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:checkInButton]; } // 更新日期标签的文本 - (void)updateDateLabel { NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; formatter.dateFormat = @"yyyy年MM月dd日"; self.dateLabel.text = [formatter stringFromDate:[NSDate date]]; } // 签到按钮点击事件 - (void)checkInButtonClicked:(UIButton *)sender { // TODO: 处理签到逻辑 // 更新日期标签的文本 [self updateDateLabel]; } @end ``` 在AppDelegate.m文件中,将ViewController设置为根视图控制器: ```objective-c #import "AppDelegate.h" #import "ViewController.h" @interface AppDelegate () @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; ViewController *viewController = [[ViewController alloc] init]; UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController]; self.window.rootViewController = navigationController; [self.window makeKeyAndVisible]; return YES; } ``` 这样就完成了一个简单的签到日期界面的实现。运行程序后,可以看到一个带有日期标签和签到按钮的界面。点击签到按钮后,日期标签上的日期会更新为当前日期。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值