我有一个NSString" dateString"其中包含给定格式的日期和时间。
"MM/dd/yyyy HH:mm:ss a"
。
我想使用NSDateFormatter
从dateString中获取数据,然后我尝试在字符串"strDate"
中显示。我能够获取数据,但唯一的问题是我没有得到"hour"
地方的正确值。
对于Ex:
dateString = 1/23/2015 7:06:37 AM
strDate = 01/23/2015 00:06:37 am
如何解决此问题。提前致谢。这是我的代码:
-(NSString *)getDateQuestion:(NSString *)dateString
{
NSLog(@"dateString = %@",dateString);
//NSString to NSDate
NSDate *datefromString = [[NSDate alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT+5:30"]];
[dateFormatter setTimeZone: [NSTimeZone systemTimeZone]];
[dateFormatter setDateFormat:@"MM/dd/yyyy HH:mm:ss a"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
datefromString = [dateFormatter dateFromString:dateString];
NSLog(@"dateString1 = %@",datefromString);
//NSDate convert to NSString
[dateFormatter setDateFormat:@"MM/dd/yyyy HH:mm:ss a"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT+5:30"]];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSString *strDate = [dateFormatter stringFromDate:datefromString];
NSLog(@"strDate = %@",strDate);
return strDate;
}
答案 0 :(得分:2)
只是将正确的日期时间字符串传递给函数并且不要设置时区一次又一次不必要...我希望它可以帮助你......
NSDate *dat = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC+05:30"]];
[dateFormatter setDateFormat:@"MM/dd/yyyy HH:mm:ss a"];
NSString * dateString =[dateFormatter stringFromDate:dat];
NSLog(@"dateString = %@",dateString);
NSLog(@"dateString1 = %@",dateString);
//NSDate convert to NSString
[dateFormatter setDateFormat:@"HH:mm:ss a"];
NSString *strDate = [dateFormatter stringFromDate:dat];
NSLog(@"strDate = %@",strDate);
HH代表24小时。
hh坐了12个小时。
答案 1 :(得分:1)
[dateFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
替换为"MM/dd/yyyy hh:mm:ss a"