2013-05-14 73 views
-4

我需要将当前日期时间转换为"04/10/2013 12:00:00 GMT+5:00"格式。 我已经通过不同的方法,但无法得到确切的格式。 任何人都可以知道,请帮助我。在iphone中转换日期时间

+0

你能提供一些代码的东西吧。 – iDeveloper 2013-05-14 08:28:49

+0

http://www.roseindia.net/tutorial/iphone/examples/iphone-datetime.html – Buntylm 2013-05-14 08:29:37

回答

0
// String To Date Conversion 
NSString *dateStr = @"5/13/2012 6:05 am"; 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"M/d/yyyy h:mm a"]; 
NSDate *myDate = [dateFormatter dateFromString:dateStr]; 

// This converts time to GMT local timezone  
NSDateFormatter* df_local = [[[NSDateFormatter alloc] init] autorelease]; 
// calculate Number of seconds upto 5hrs(GMT+5000) seconds = 18000, if its GMT+0530 then seconds = 19800 
// Set TimeZone Accordingly 
[df_local setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:18000]]; 
// Set your Date Formate 
[df_local setDateFormat:@"MM/dd/yyyy hh:mm:ss"]; 

// Your Final Output String 
NSString* ts_local_string = [NSString stringWithFormat:@"%@ %@",[df_local stringFromDate:myDate],[[df_local timeZone] name]]; 
NSLog(@"Final string : %@",ts_local_string); 

NSString* anotherFormat = [NSString stringWithFormat:@"%@ %@",[df_local stringFromDate:myDate],[[df_local timeZone] abbreviation]]; 
NSLog(@"OUtput : %@",anotherFormat); 

OUTPUT:最终的字符串:2012年5月13日五时35分00秒GMT + 0500

+0

如何将时区作为GMT + 05:00而不是GMT + 0500 – krishna 2013-05-14 09:23:56

+0

我已经按照所需的格式编辑了答案。 ,让我知道见解。 – 2013-05-14 09:31:21

0
NSDateFormatter *format = [[NSDateFormatter alloc] init]; 
[format setDateFormat:@"MMM, dd, yyyy HH:mm:ss Z"]; 

NSDate *now = [NSDate date]; 

NSString *dateString = [format stringFromDate:now]; 
2
NSDate *myDate = [NSDate date]; 
NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
[formatter setDateFormat:@"dd/MM/yyyy hh:mm:ss ZZZ"]; 
NSString * dateString = [formatter stringFromDate:myDate]; 

这将是在12个小时的格式。如果你想24小时格式替换HH与HH。