开发者

creating formatted NSDate using NSDateFormatter or mktime

开发者 https://www.devze.com 2023-02-10 01:32 出处:网络
I\'m just trying to create a NSDate object with string as:2011-02-10 4:30:45 Take a look at the code: Approach OBJC:

I'm just trying to create a NSDate object with string as:2011-02-10 4:30:45

Take a look at the code:

Approach 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;
}

And here's the output:


1> 2011-02-10 4:30:45
2> 2011-02-09 23:00:45 +0000
3> 2011-02-10 04:30:45

So why is 2> getting printed wrong?

Suppose at 2011-02-10 4:20:45, I try setting up a LocalNotification with that date, it fires instantly because the processor assumes the time is already expired!


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];

And, I've already tried setting up various TimeZones and NSLocale for en_US, en_FR. No help.

Approach C:

And FYI now I'm switching to C, trying something with:


-(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]);
    开发者_JS百科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;
}

Output: ans: -1.000000

There again I'm stuck with converting time_t to NSTimeInterval.

So, thanks in advance if you could help me out with any approach :(


In your input string and format yyyy-MM-dd HH:mm:ss you didn't specify the timezone. So it defaults to UTC.

0

精彩评论

暂无评论...
验证码 换一张
取 消