簡體   English   中英

iOS將帶有am,pm的日期字符串轉換為NSDate(設備設置為24小時格式)

[英]iOS converting date string with am, pm to NSDate (Device setting with 24 hour format)

我有這樣的日期時間字符串。

2017年2月20日03:32 PM //這是新加坡時間。 所以我需要選擇新加坡時區

我嘗試像這樣轉換為NSDate。

NSDate *redeemDate = [NSDate dateWithString:currentDateString formatString:@"dd MMM yyyy hh:mma" timeZone:[NSTimeZone timeZoneForSecondsFromGMT:8*3600]];

我雖然使用這個圖書館。 但是如果我手動格式化也是如此。 https://github.com/MatthewYork/DateTools

如果設備使用12小時格式,則可以,但是如果使用24小時格式,則表示無效。 我可以知道為什么嗎? 我以為可能是因為hh而我改成了HH 但這也不行。

HH:mm =>看起來像00:12,23:00 ...這是24小時格式。

hh:mm =>看起來像01:00Am,02:00Am ...... 01:00 pm,格式為12小時。

因此,如果要以其他時間/日期格式顯示,則必須轉換為適當的格式。

在這里看看http://www.unicode.org/reports/tr35/tr35-19.html#Date_Format_Patterns

例:

NSDate *date = [NSDate new];
NSString* format = @"dd MMM yyyy hh:mma'Z'";

NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
NSCalendar *calendar = [NSCalendar currentCalendar];
calendar.timeZone = [NSTimeZone timeZoneWithName:@"SGT"];

[dateFormat setDateFormat:format];
[dateFormat setCalendar: calendar];

NSDate* formatDate = [dateFormat dateFromString:[dateFormat stringFromDate:date]];

你可以試試這個嗎?

您正在使用的庫是錯誤的。 您需要在NSDateFormatter上設置其他未設置的參數,這些參數正在使用系統設置。 不要使用DateTool只是創建您自己的NSDateFormatter 除了時區和formatString之外,還必須設置日歷語言環境

參見https://developer.apple.com/library/content/qa/qa1480/_index.html

暫無
暫無

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

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