2011-11-24 18 views
18

Tôi đang sử dụng định dạng ngày để nhận ngày và giờ trong đơn đăng ký của mình. Nhưng tôi đang gặp phải sự cố khi tôi thay đổi ngôn ngữ của trình định dạng ngày của điện thoại trả về ngày và giờ của ngôn ngữ được chọn của điện thoại do ứng dụng của tôi gặp sự cố do chúng tôi không hỗ trợ nhiều ngôn ngữ. Bất cứ ai có thể vui lòng giúp tôi trong việc này.Nsdateformatter trả về ngày của tôi bằng ngôn ngữ của điện thoại được chọn. Có thể trả lại cho tôi chỉ tiếng Anh mọi lúc không?

hãy tìm đoạn mã dưới đây:

NSDate *date=[NSDate date]; 
NSDateFormatter *objTimeFotmatter=[[NSDateFormatter alloc]init]; 
[objTimeFotmatter setDateFormat:@"HH:mm"]; 

NSDateFormatter *objDayFotmatter=[[NSDateFormatter alloc]init]; 
[objDayFotmatter setDateFormat:@"EEEE"]; 

NSString *objTime=[objTimeFotmatter stringFromDate:date]; 
NSString *objDay=[objDayFotmatter stringFromDate:date]; 

NSLog(@"objTime=%@",objTime); 
NSLog(@"objDay=%@",objDay); 

Khi tôi chọn ngôn ngữ điện thoại như Gujrati (Ấn Độ) sản lượng mà tôi đang nhìn thấy bằng cách sử dụng NSLog sử dụng này là như sau,

2011-11-24 11:23:20.221 Belkin_Plugin[1110:707] objTime=૧૧:૨૩ 
2011-11-24 11:23:20.227 Belkin_Plugin[1110:707] objDay=ગુરુવાર 
+0

này có thể là cùng một câu hỏi [như này] (http://stackoverflow.com/questions/1348590/how-to-make-nsdateformatter-display-locale-specific -ngày) ??? –

+0

@breakfreehg: Hãy nhìn vào câu trả lời của tôi. Nó làm việc cho tôi và sẽ làm việc cho bạn. :] –

Trả lời

45

Thêm các dòng sau vào định dạng ngày tháng.

NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; 
[dateFormatter setLocale:usLocale]; 

Trong trường hợp của bạn,

NSDateFormatter *objTimeFotmatter=[[NSDateFormatter alloc]init]; 
[objTimeFotmatter setDateFormat:@"HH:mm"]; 
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; 
[objTimeFotmatter setLocale:usLocale]; 

Tương tự như vậy cho tất cả dateformatters.

1

Hãy thử với mã này:

NSDate *date=[NSDate date]; 
NSDateFormatter *objTimeFotmatter=[[NSDateFormatter alloc]init]; 
[objTimeFotmatter setDateFormat:@"HH:mm"]; 
[objTimeFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] 
autorelease]]; 
NSDateFormatter *objDayFotmatter=[[NSDateFormatter alloc]init]; 
[objDayFotmatter setDateFormat:@"EEEE"]; 
[objDayFotmatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] 
autorelease]]; 
NSString *objTime=[objTimeFotmatter stringFromDate:date]; 
NSString *objDay=[objDayFotmatter stringFromDate:date]; 
[objDayFotmatter release]; 
[objTimeFormatter release]; 

NSLog(@"objTime=%@",objTime); 
NSLog(@"objDay=%@",objDay); 

Hy vọng điều này sẽ giúp bạn.

1

Swift

let dateFormatter = DateFormatter() 
dateFormatter.locale = NSLocale(localeIdentifier: "en_US") as Locale! 
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss" 
let resultsDate = dateFormatter.string(from: date)