How to Fetch date and time from a formatted string in iOS

妖精的绣舞 提交于 2019-12-12 00:39:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!