简体   繁体   English

将日期时间从NSString转换为NSDate

[英]Convert date time to NSDate from NSString

Time zone always made trouble for me. 时区总是给我带来麻烦。 This time I have to convert date-time , that I have in NSSTring to NSDate. 这次我必须将NSSTring中的date-time转换为NSDate。

I am doing something like this. 我正在做这样的事情。

NSString *myStringDate=@"14-11-2012 4:09:00 PM +0500"

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone systemTimeZone]];
[formatter setDateFormat:@"dd-MM-yyyy h:mm:ss a Z"];

NSDate *aDate = [formatter dateFromString:myStringDate];
NSLog(@"%@",aDate);

but I am having the output like this 但我有这样的输出

14-11-2012 11:09:00 +0000

Also, no AM/PM is setting :-( 另外,没有设置AM / PM :-(

What I want is 14-11-2012 4:09:00 PM +0500 ie same Date-Time that I have in string. 我想要的是14-11-2012 4:09:00 PM +0500即我在字符串中具有的相同日期时间。

Thanks in anticipation. 谢谢您的期待。

the output of your converting is giving the GMT time 转换的输出给了GMT时间

NSString *myStringDate=@"14-11-2012 4:09:00 PM +0500"

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone systemTimeZone]];
[formatter setDateFormat:@"dd-MM-yyyy h:mm:ss a Z"];

NSDate *aDate = [formatter dateFromString:myStringDate];



 NSDateFormatter* df_utc = [[[NSDateFormatter alloc] init] autorelease];
 [df_utc setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
 [df_utc setDateFormat:@"yyyy.MM.dd G 'at' HH:mm:ss zzz"];

 NSDateFormatter* df_local = [[[NSDateFormatter alloc] init] autorelease];
 [df_local setTimeZone:[NSTimeZone timeZoneWithName:@"EST"]];
 [df_local setDateFormat:@"yyyy.MM.dd G 'at' HH:mm:ss zzz"];

 NSString* ts_utc_string = [df_utc stringFromDate:aDate];
 NSString* ts_local_string = [df_local stringFromDate:aDate];

Here Is the Change need to be taken. 这是需要采取的变更。

[formatter setDateFormat:@"dd-MM-yyyy h:mm:ss a "];

Thanks 谢谢

The conversion looks correct, but the default output is in UTC time ( +0000 ) and with a 24h clock which is why you don't get the AM/PM distinction (“01:00 PM” would be 13:00). 转换看起来正确,但是默认输出为UTC时间( +0000 )并带有24小时制,这就是为什么您无法获得AM / PM区别的原因(“ 01:00 PM”为13:00)。 You also need to format the output if you want a specific representation ( [formatter stringFromDate:aDate] )… 如果需要特定的表示形式,还需要格式化输出[formatter stringFromDate:aDate] )…

For the UTC issue you need to select the time zone of your choice, by giving that choice in place of [NSTimeZone systemTimeZone] . 对于UTC问题,您需要通过选择该时区来代替[NSTimeZone systemTimeZone]来选择该时区。 Try [NSTimeZone localTimeZone] for starters. 尝试使用[NSTimeZone localTimeZone]作为初学者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM