无法从 NSString 获取 NSDate
我可以使用以下代码获取表示 PST 中当前日期和时间的 NSString。
//get current date and time
NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"America/Los_Angeles"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/yy HH:mm:ss zzz"];
[dateFormatter setTimeZone:timeZone];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[dateFormatter setLocale:enUSPOSIXLocale];
[enUSPOSIXLocale release];
NSDate *date = [NSDate date];
NSString *currentDateStr = [dateFormatter stringFromDate:date];
NSLog(@"currentDateStr %@",currentDateStr);
[dateFormatter release];
编辑:
但是以下从 NSString 获取 NSDate 的代码不符合我的目的。
//get date from string
NSDateFormatter* formatter2 = [[NSDateFormatter alloc] init];
[formatter2 setDateFormat:@"MM/dd/yy HH:mm:ss"];
NSDate *dt = [[NSDate alloc]init];
dt = [formatter2 dateFromString:currentDateStr];
NSLog(@"dt %@",dt);
“dt”似乎为空。
有人可以帮我解决从 NSString 获取 NSDate 的问题吗? 提前致谢。
I am able to fetch NSString representing the current date and time in PST using the following code.
//get current date and time
NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"America/Los_Angeles"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/yy HH:mm:ss zzz"];
[dateFormatter setTimeZone:timeZone];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[dateFormatter setLocale:enUSPOSIXLocale];
[enUSPOSIXLocale release];
NSDate *date = [NSDate date];
NSString *currentDateStr = [dateFormatter stringFromDate:date];
NSLog(@"currentDateStr %@",currentDateStr);
[dateFormatter release];
EDIT:
But the following code to fetch NSDate from NSString doesn't serve my purpose.
//get date from string
NSDateFormatter* formatter2 = [[NSDateFormatter alloc] init];
[formatter2 setDateFormat:@"MM/dd/yy HH:mm:ss"];
NSDate *dt = [[NSDate alloc]init];
dt = [formatter2 dateFromString:currentDateStr];
NSLog(@"dt %@",dt);
"dt" appears to be null.
Could anybody help me out in solving this issue of getting NSDate from NSString.
Thanx in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
NSDateFormatter
还具有dateFromString:
函数。编辑:
NSDateFormatter
also hasdateFromString:
function.EDIT:
利用
在您的情况下
urString
是currentDateStr
Make use of
In your case
urString
iscurrentDateStr
使用
Use