将浮点数转换为时间

时间:2012-09-05 10:39:55

标签: iphone objective-c ipad ios5

我有一个字符串值20.30(小时)我需要它转换08:30:00。 任何人都知道这个请帮助我。

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    dateFormat.dateFormat = @"hh:mm:ss";
    [dateFormat setTimeZone:[NSTimeZone systemTimeZone]];

    double time = 20.30;
    double timeInSeconds = time*24*60*60; // 0.27392 * 24 = 6.57408 hours *60 for minutes * 60 for seconds

    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:timeInSeconds]; //Creates a date: 1 January 2001 6:34:27 AM, GMT

    NSLog(@"Time: %@", [dateFormat stringFromDate:date]);
    [dateFormat release];

以上代码对我不起作用。

5 个答案:

答案 0 :(得分:2)

用以下代码替换您的代码:

//The Format which you want as output
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
dateFormat.dateFormat = @"hh:mm:ss";
[dateFormat setTimeZone:[NSTimeZone systemTimeZone]];

//The Format in which your dateTime currently is
NSDateFormatter *dateFormat1 = [[NSDateFormatter alloc] init];
dateFormat1.dateFormat = @"HH.mm";
[dateFormat1 setTimeZone:[NSTimeZone systemTimeZone]];

double time = 20.30;

NSString *timeStr = [NSString stringWithFormat:@"%.2f",time];
NSDate *dates = [dateFormat1 dateFromString:timeStr];
NSLog(@"Time: %@", [dateFormat stringFromDate:dates]);

答案 1 :(得分:0)

尝试这是否有效:

[dateFormatter setDateFormat:@"HH:mm 'on' dd MMMM YYYY"];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]];  

答案 2 :(得分:0)

用于计算秒数的公式是错误的。

您可以使用类似

的内容
double t = 20.30;

int hours = (int) floor(t);
int minutes = (int) ((t-hours)*100);

int seconds = hours*60*60 + minutes*60;

NSLog(@"%@",[NSDate dateWithTimeIntervalSinceNow:seconds]);

答案 3 :(得分:0)

试试这个:

double time = 20.30;
NSString *strTime = [NSString stringWithFormat:@"%.2f",time];
NSArray *values = [strTime componentsSeparatedByString:@"."];

double hours = [values objectAtIndex:0];
double min = [values objectAtIndex:1];

NSDate *date = [NSDate dateWithTimeIntervalSinceNow:(hours*60*60)+mins*60]; 
NSLog(@"Time: %@", [dateFormat stringFromDate:date]);

答案 4 :(得分:0)

试试这个

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
dateFormat.dateFormat = @"HH:mm";
[dateFormat setTimeZone:[NSTimeZone systemTimeZone]];

double time = 20.30;
NSString* timeString=[NSString stringWithString:[[NSString stringWithFormat:@"%.2f",time]stringByReplacingOccurrencesOfString:@"." withString:@":"]];

NSDate *date = [dateFormat dateFromString:timeString];
dateFormat.dateFormat=@"hh:mm:ss";
NSLog(@"Time: %@", [dateFormat stringFromDate:date]);

这将转换为20.30至08:30:00