我有一个像这样的 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
CLLocation 返回负速度CLLocation returning negative speed(CLLocation 返回负速度)
通过 NSFetchedResultsController 按距离排序的核心数据Locations in Core Data sorted by distance via NSFetchedResultsController?(通过 NSFetchedResultsController 按距离排序的核心数据中的位置?
Swift:用户位置附近的地理围栏/地理位置Swift: Geofencing / geolocations near user location(Swift:用户位置附近的地理围栏/地理位置)
如何在 iOS 上的变量中获取位置(纬度和经度值)How to get Location (latitude amp; longitude value) in variable on iOS?(如何在 iOS 上的变量中获取位置(纬度和经度值)?)
如何使用 Phonegap 跟踪设备位置(iOS 和 Android)设备How to track the device location (iOS and Android) device using Phonegap(如何使用 Phonegap 跟踪设备位置(iOS 和 Android)设备)
从 iOS 获取反向地理编码当前位置的最简单方法Easiest way of getting reverse geocoded current location from iOS(从 iOS 获取反向地理编码当前位置的最简单方法)