-2

我有一个字符串值 20.30(hours) 我需要它来转换 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];

上面的代码对我不起作用。

4

5 回答 5

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]);
于 2012-09-05T10:56:28.183 回答
0

试试这是否有效:

[dateFormatter setDateFormat:@"HH:mm 'on' dd MMMM YYYY"];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]];  
于 2012-09-05T10:52:04.907 回答
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]);
于 2012-09-05T10:52:31.417 回答
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]);
于 2012-09-05T10:54:47.233 回答
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

于 2012-09-05T11:02:07.397 回答