2016-03-31 9 views
0

複数の分で構成されたクロック文字列を解析し、NSDateFormatterを使用してNSDateに変換しようとしています。NSDateに複数分の数字(2分以上)を変換する

解析しようとしている文字列の例は、@"1234:56"です.1234は時計の分、56は秒です。 @"mmmm:ss"などの形式を使用しようとしましたが、nilが返されました。

これが可能な場合は、誰でも私にこれを手伝ってもらえますか?

おかげ

+2

"mmmm:ss"などのフォーマットはありません – Joshua

答えて

1

のようなもの:ssの後、私のアプローチは次のようになりますあなたは何をしたいが、私はそのような何かをお勧め:

NSArray *timeArray = [@"1234:56" componentsSeparatedByString:@":"]; 
NSUInteger minutes = [[timeArray firstObject] integerValue]; 
NSUInteger seconds = [[timeArray lastObject] integerValue]; 

NSTimeInterval totalSeconds = minutes*60+seconds; 

そして、あなたは新しい日付オブジェクトや仕事を作成する必要がありますこれとともに。

NSDate *newDate = [NSDate dateWithTimeIntervalSince1970:totalSeconds]; 
+0

ありがとうございます。私は時計の時間に注意を払うだけで(そして、日、月、年を無視して)私はそれを正しく解析することができるだろうと思う。 – CRoig

1

NSDateFormatterが唯一の合法日付形式で動作していないと何がある「mmmm'.Youは自分で日付を取得する必要があります。

NSString *str = @"234:56"; 
NSArray<NSString *> *components = [str componentsSeparatedByString:@":"]; 
NSInteger minute = 0; 
NSInteger second = 0; 
switch (components.count) { 
    case 1: 
     second = components[0].integerValue; 
     break; 
    case 2: 
     second = components[0].integerValue; 
     minute = components[1].integerValue; 
     break; 

    default: 
     break; 
} 
// then convert to hours. 
0

はこれを試してみてください。

NSDate *currentDate = [NSDate date]; 
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate]; 
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval]; 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"HH:mm:ss.SSS"]; 
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]]; 
NSString *timeString=[dateFormatter stringFromDate:timerDate]; 
self.timerLabel.text = timeString; 
0

あなたはHHにそれを変換したい場合:MM:

// assuming you wouldn't have any hours in the string and format will always be minutes:seconds 

NSArray *timeArray = [@"1234:56" componentsSeparatedByString:@":"]; 

//array's firstObject will be the "minutes/Hours" 
NSString *minutesAndHours = [timeArray firstObject]; 
int hours = [minutesAndHours intValue]/60; 
int minutes = [minutesAndHours intValue]%60; 
int seconds = [timeArray lastObject]; 

//create the format 

NSString *time = [NSString stringWithFormat:@"%d:%d:%d",hours,minutes,seconds]; 

//then use the time format 
NSString *time = [NSString stringWithFormat:@"%d:%d:%d",hours,minutes,seconds]; 
NSDateFormatter *format = [NSDateFormatter new]; 
[format setDateFormat:@"HH:mm:ss"]; 
NSDate *date = [format dateFromString:time]; 

私はそのことについてはよく分からないこの

関連する問題