从字符串创建 NSDate

create a NSDate from a string(从字符串创建 NSDate)
本文介绍了从字符串创建 NSDate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的 NSString:@"3/15/2012 9:15 PM" 我想把它转换成 NSDate,我是这样做的:

I have an NSString like this: @"3/15/2012 9:15 PM" and I would like to convert it to NSDate, I have done like this:

NSString *str =@"3/15/2012 9:15 PM";
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"mm/dd/yyyy HH:mm"];
NSDate *date = [formatter dateFromString:];

NSLog(@"%@", date);  // date = null

你能帮帮我吗,谢谢.

推荐答案

使用如下解决方案

NSString *str = @"3/15/2012 9:15 PM";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

formatter.dateFormat = @"MM/dd/yyyy HH:mm a";

NSDate *date = [formatter dateFromString:str];

NSLog(@"%@", date);

对不起,格式应该如下:

Sorry, the format should be as follows:

formatter.dateFormat = @"MM/dd/yyyy hh:mm a";

显示的时间将是格林威治标准时间.因此,如果您添加/减去时区,将是晚上 9:15.

And the time shown will be GMT time. So if you add/subtract the timezone, it would be 9:15 PM.

#2

如下使用.你也会得到准确的时间.

Use as below. You would get exact time too.

NSString *str = @"3/15/2012 9:15 PM";

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

formatter.dateFormat = @"MM/dd/yyyy hh:mm a";

NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];

formatter.timeZone = gmt;

NSDate *date = [formatter dateFromString:str];

NSLog(@"%@",date);

这篇关于从字符串创建 NSDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why local notification is not firing for UNCalendarNotificationTrigger(为什么没有为UNCalendarNotificationTrigger触发本地通知)
iOS VoiceOver functionality changes with Bundle Identifier(IOS画外音功能随捆绑包标识符而变化)
tabbar middle tab out of tabbar corner(选项卡栏中间的选项卡角外)
Pushing UIViewController above UITabBar(将UIView控制器推送到UITabBar上方)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)
Get an event when UIBarButtonItem menu is displayed(显示UIBarButtonItem菜单时获取事件)