簡體   English   中英

以12小時時間格式轉換NSString

[英]Convert NSString in 12 hour time format

在我的項目中,我有一個包含這樣的數據的NSString

NSString *s=@"20";

我想將其轉換為“08:00”。 我怎樣才能做到這一點?

我試過這個:

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"hh:mm a"];
NSString* dateString = [dateFormatter stringFromDate:@"20"];

但我得到這個dateString為空值。

您輸入為NSString ,需要輸出為NSString

因此不需要NSDateNSDateFormatter中間工作。

你可以通過以下方式達到:

NSString *s=@"20";
NSString *time=[NSString stringWithFormat:@"%d:00",[s integerValue]%12];

請嘗試使用這個。我希望它能正常工作......

NSString *s=@"20";    
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"HH"];
NSDate *date = [df dateFromString:s];

[df setDateFormat:@"hh:mm a"];
NSString *newTime = [df stringFromDate:date];
NSLog(@"Time : %@",newTime);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM