iphone - ios:字符串到日期的转换

标签 iphone ios ipad

我正在尝试使用以下代码将日期从NSString转换为NSDate

NSDateFormatter *dateformatter = [[NSDateFormatter alloc]init];
[dateformatter setDateStyle:NSDateFormatterShortStyle];
[dateformatter setTimeStyle:NSDateFormatterNoStyle];
[dateformatter setDateFormat:@"dd/MM/yyyy"];
NSDate *myDate = [[NSDate alloc] init];

currMonth = 3;
currYear = 2012;
NSString *str = [NSString stringWithFormat:@"01/%2d/%d", currMonth, currYear];
str = [str stringByReplacingOccurrencesOfString:@" " withString:@"0"];
myDate = [dateformatter dateFromString:str];
NSLog(@"myStr: %@",str);
NSLog(@"myMonth: %2d",currMonth);
NSLog(@"myYear: %d",currYear);
NSLog(@"myDate: %@",myDate);

上面的代码给我错误的日期。谁能帮忙吗?

最佳答案

你的输出是什么?请记住,NSDate位于UTC中。
2012-03-01 00:00:00 (GMT+1)2012-02-39 23:00:00 (UTC)
另一个提示:
%02用前导零格式化您的整数。

关于iphone - ios:字符串到日期的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10138271/

相关文章:

ios - View 不再位于 View 堆栈顶部时的事件

ios - 默认 UICollectionView 布局不尊重 iPad 分屏

javascript - JavaScript 中的 iPad 版本检测

iphone - 确定是否选择了特定的UITextField

iphone - 在 iPhone 上将声音录制为 WAV

iphone - UIImagePickerController 媒体类型 kUTTypeMovie 运行时异常

ios - 如何创建一个在不活动后返回到先前状态的 iOS webapp?

c++ - Xcode 7 不使用 C++ 框架构建项目

javascript - 如何让备用样式表在 iOS5 Safari 上工作?

iphone - 给定文件和目录生成相对路径的 Objective-C 代码