%@",dstr); ..." />

使用NSDateFormatter或mktime创建格式化的NSDate

我只是想用字符串创建一个
NSDate
对象:
2011-02-10 4:30:45
看看代码: 方法OBJC:
-(NSDate *)get_date_df:(NSString *)dstr
{
    NSLog(@"1> %@",dstr);

    NSDateFormatter *df_in = [[[NSDateFormatter alloc] init]autorelease];
    [df_in setDateFormat:@"yyyy-MM-dd HH:mm:ss"];   
    NSDate *d = [df_in dateFromString:dstr];

    NSLog(@"2> %@",d);

    NSLog(@"3> %@",[df_in stringFromDate:d]);

    return d;
}
这是输出:
1> 2011-02-10 4:30:45
2> 2011-02-09 23:00:45 +0000
3> 2011-02-10 04:30:45
那么为什么
2>
打印错了? 假设在
2011-02-10 4:20:45
,我尝试设置具有该日期的LocalNotification,它会立即触发,因为处理器假定时间已经过期!
UILocalNotification *lnf = [[UILocalNotification alloc] init];
[lnf setFireDate:[self get_date_df:@"2011-02-10 4:30:45"]];
[lnf setAlertBody:@"WTF"];
[[UIApplication sharedApplication]scheduleLocalNotification:lnf];
[lnf release];
并且,我已经尝试为
en_US, en_FR
设置各种
TimeZones
NSLocale
。没有帮助。 方法C: 现在,我正在切换到C,尝试以下方法:
-(NSDate *)get_date_c:(const char *)date_str
{
    char date[10][6] = {0};
    sscanf(date_str,"%[0-9] - %[0-9] - %[0-9] %[0-9] : %[0-9] : %[0-9]",date[0],date[1],date[2],date[3],date[4],date[5]);   

    struct tm *t_info = (struct tm *)malloc(sizeof(struct tm));
    t_info->tm_sec = atoi(date[5]);
    t_info->tm_min = atoi(date[4]);
    t_info->tm_hour = atoi(date[3]);
    t_info->tm_mday = atoi(date[2]);
    t_info->tm_mon = atoi(date[1]);
    t_info->tm_year = atoi(date[0]);
    NSLog(@"ans: %f",(double)mktime(t_info));
    NSDate *d = [NSDate dateWithTimeIntervalSince1970:mktime(t_info)];
    free(t_info);
    return d;
}
输出:
ans: -1.000000
我再次将
time_t
转换为
NSTimeInterval
。 所以,如果你能帮我解决任何问题,请提前感谢:(     
已邀请:
在输入字符串和格式yyyy-MM-dd HH:mm:ss中,您没有指定时区。所以它默认为UTC。     

要回复问题请先登录注册