问题
I have a NSString "dateString" which contains date and time in given format.
"MM/dd/yyyy HH:mm:ss a".
I want to fetch the data from the dateString using NSDateFormatter and then I'm trying to show in a String "strDate". I.m able to fetch the data but the only issue is that i'm not getting the correct value for "hour" place.
For Ex:
dateString = 1/23/2015 7:06:37 AM
strDate = 01/23/2015 00:06:37 am
How to resolve this issue. Thanks in advance. This is my code:
-(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;
}
回答1:
Just Pass Correct date Time string to the function and don't set time zone Unnecessary again and again... i hope it helps you...
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 stands for 24hr.
hh satnds for 12 hr.
回答2:
[dateFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
Replace with "MM/dd/yyyy hh:mm:ss a"
来源:https://stackoverflow.com/questions/28643448/how-to-fetch-date-and-time-from-a-formatted-string-in-ios